Remove all nil elements from an array with compact

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents