The compact
method in Ruby returns an array that contains non-nil elements. This means that when we call this method on an array that contains nil elements, it removes them. It only returns the other, non-nil, elements of the array.
array.compact
It does not take any parameters. It can only be used with an array.
This method returns an array containing non-nil elements.
In the program below, we demonstrate the use of the compact
method. We list arrays containing nil
elements. Then, we call the compact
method, and print the returned values to the console.
# Create arraysarr1 = [1, nil, 2, nil, 3]arr2 = ["a", "b", "c", "d"]arr3 = [true, false, nil]arr4 = ["Meta", "Apple", "nill",nil]# Call the compact methoda = arr1.compactb = arr2.compactc = arr3.compactd = arr4.compact# Print the returned valuesputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"
The code above shows that any element whose value is nil
is eliminated, while non-nil elements are returned.
nil
elements.compact
method on the arrays.