使用 compact 从数组中删除所有 nil 元素

如果一个阵列恰好有一个或多个 nil 元素并且需要删除这些元素,则可以使用 Array#compactArray#compact! 方法,如下所示。

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]

最后,请注意,如果在没有 nil 元素的数组上调用 #compact#compact!,则这些元素将返回 nil。

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

array.compact # => nil

array.compact! # => nil