How to Remove All "nil" Values From a Ruby Array?

You can remove all nil values in a Ruby array in the following ways:

Using Array#compact

The Array#compact method returns a new array with all nil values removed:

arr = [1, 2, nil, 3, nil, 4, 5, nil]
new_arr = arr.compact

print new_arr #=> [1, 2, 3, 4, 5]

You may also mutate the original array by using Array#compact! (instead of Array#compact), for example, like so:

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

print arr #=> [1, 2, 3, 4, 5]

Using Array#reject

The Array#reject method allows you to exclude values that return true in its block. You can use this to exclude all nil values in an array in the following way:

arr = [1, 2, nil, 3, nil, 4, 5, nil]
new_arr = arr.reject { | item | item == nil }

print new_arr #=> [1, 2, 3, 4, 5]

This returns a new array with all nil values removed. You can also shorten this by using the &: syntax, for example, like so:

arr = [1, 2, nil, 3, nil, 4, 5, nil]
new_arr = arr.reject(&:nil?)

print new_arr #=> [1, 2, 3, 4, 5]

You may also mutate the original array by using Array#reject! (instead of Array#reject), for example, like so:

arr = [1, 2, nil, 3, nil, 4, 5, nil]
arr.reject!(&:nil?)

print arr #=> [1, 2, 3, 4, 5]

Using Array#filter

Introduced in Ruby 2.6, you can use the Array#filter method to only include values that are not nil in the resulting array:

# Ruby 2.6+
arr = [1, 2, nil, 3, nil, 4, 5, nil]
new_arr = arr.filter { | item | item != nil }

print new_arr #=> [1, 2, 3, 4, 5]

This would return a new array excluding all nil values. You may also mutate the original array by using Array#filter! (instead of Array#filter), for example, like so:

# Ruby 2.6+
arr = [1, 2, nil, 3, nil, 4, 5, nil]
arr.filter! { | item | item != nil }

print arr #=> [1, 2, 3, 4, 5]

Please note that Array#filter and Array#filter! are aliases of Array#select and Array#select! respectively, and have no performance benefit over each other. Therefore, you can simply use Array#select in versions of Ruby prior to v2.6.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.