Remove all nil elements from an array with compact
suggest changeArray#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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents