Ruby Language Arrays Remove all nil elements from an array with #compact

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

If an array happens to have one or more nil elements and these need to be removed, the Array#compact or Array#compact! methods can be used, as below.

array = [ 1, nil, 'hello', nil, '5', 33]

array.compact # => [ 1, 'hello', '5', 33]

#notice that the method returns a new copy of the array with nil removed,
#without affecting the original

array = [ 1, nil, 'hello', nil, '5', 33]

#If you need the original array modified, you can either reassign it

array = array.compact # => [ 1, 'hello', '5', 33]

array = [ 1, 'hello', '5', 33]

#Or you can use the much more elegant 'bang' version of the method

array = [ 1, nil, 'hello', nil, '5', 33]

array.compact # => [ 1, 'hello', '5', 33]

array = [ 1, 'hello', '5', 33]

Finally, notice that if #compact or #compact! are called on an array with no nil elements, these will return nil.

array = [ 'foo', 4, 'life']

array.compact # => nil

array.compact! # => nil


Got any Ruby Language Question?