How To Remove Nil From Array Ruby

When working with arrays in Ruby, you might come across a situation where you need to remove all nil elements from the array. In this blog post, we will explore a few different ways to accomplish this task.

Using the compact Method

The simplest and most straightforward way to remove nil elements from an array is by using the compact method. This method returns a new array without any nil elements. Here’s an example:

    array = [1, 2, nil, 3, nil, 4]
    array_without_nil = array.compact
    puts array_without_nil.inspect
    

Output:

[1, 2, 3, 4]

Using the compact! Method

If you want to remove nil elements from the array in-place (i.e., without creating a new array), you can use the compact! method. This method removes all nil elements from the array and returns nil itself if no changes were made. Here’s an example:

    array = [1, 2, nil, 3, nil, 4]
    array.compact!
    puts array.inspect
    

Output:

[1, 2, 3, 4]

Using the delete Method

Another way to remove nil elements from an array is by using the delete method. This method deletes all occurrences of the specified element from the array. Here’s an example:

    array = [1, 2, nil, 3, nil, 4]
    array.delete(nil)
    puts array.inspect
    

Output:

[1, 2, 3, 4]

Using the reject Method

You can also remove nil elements from an array using the reject method. This method returns a new array without the elements for which the given block returns true. Here’s an example:

    array = [1, 2, nil, 3, nil, 4]
    array_without_nil = array.reject { |element| element.nil? }
    puts array_without_nil.inspect
    

Output:

[1, 2, 3, 4]

Using the reject! Method

Similarly to the compact! method, you can use the reject! method if you want to remove nil elements from the array in-place. This method returns nil if no changes were made. Here’s an example:

    array = [1, 2, nil, 3, nil, 4]
    array.reject! { |element| element.nil? }
    puts array.inspect
    

Output:

[1, 2, 3, 4]

Conclusion

As you can see, Ruby offers several ways to remove nil elements from an array. Choose the one that best fits your needs and coding style. Happy coding!