使用 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