Remove all nil elements from an array with compact

suggest change

Array#compact returns a new array with every nil removed. The receiver is unchanged. compact! changes the receiver and returns it, or returns nil if there was no nil to remove.

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

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

array = array.compact # replace the variable with the copy

array = [1, nil, "hello", nil, "5", 33]
array.compact! # => [1, "hello", "5", 33]
array          # => [1, "hello", "5", 33]

array = ["foo", 4, "life"]
array.compact  # => ["foo", 4, "life"]
array.compact! # => nil

Feedback about page:

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



Table Of Contents