When you want to remove nil
elements from a Ruby array, you can use two methods: compact
or compact!
. They both remove nil
elements, but compact!
removes them permanently.
In this shot, we will be talking about the compact!
method. This method is used to remove every nil
element in an array permanently.
array.compact!
This method does not take any parameters. It only needs an array to call the method.
This method returns the original array with all nil
values removed. If nothing is removed, then nil
or nothing is returned.
In the code example below, the use of compact!
is demonstrated. With the use of this method, all nil
values are removed.
# create arraysarr1 = [1, nil, 2, 3, nil]arr2 = ["a", "b", "c"]arr3 = [true, false, nil]arr4 = ["nil", nil, "true", "false"]# remove nil valuesarr1.compact!arr2.compact!arr3.compact!arr4.compact!# print the modified arraysputs "#{arr1}"puts "#{arr2}"puts "#{arr3}"puts "#{arr4}"