geekelo / dsa_practice

This repo is maintained just for the purpose of daily data structures and algorithm practice and proficiency
1 stars 0 forks source link

How do you remove nil values in array using Ruby? #5

Open geekelo opened 5 months ago

geekelo commented 5 months ago

You can remove nil values from an array in Ruby using various methods. Here are a few approaches:

  1. Using compact method: The compact method removes nil values from an array.

    my_array = [1, 2, nil, 3, nil, 4]
    result_array = my_array.compact

    After this, result_array will contain [1, 2, 3, 4].

  2. Using reject method: The reject method can be used to exclude elements that meet a certain condition, and you can use it to exclude nil values.

    my_array = [1, 2, nil, 3, nil, 4]
    result_array = my_array.reject { |item| item.nil? }

    After this, result_array will also contain [1, 2, 3, 4].

  3. Using compact! method (modifies the original array): The compact! method removes nil values from the array in place.

    my_array = [1, 2, nil, 3, nil, 4]
    my_array.compact!

    After this, my_array will be [1, 2, 3, 4].

Choose the method that best fits your use case. If you want to keep the original array unchanged, use compact or reject to create a new array without modifying the original one. If you don't mind modifying the original array, you can use compact!.