What is array.compact() in Ruby language?

The array.compat() method

array.compact() is a Ruby method that removes all nil values from an array and returns the array without any nil values.


This method does not change or modify the original array. It only returns a copy of the array without nil values.

Syntax


array.compact()

Parameter

The compact() method is only called on arrays. It takes no parameters.

Return value

A copy of array is returned without any nil value in it.

Code

In the below code, we create different arrays. Then, we call the compact() method on them. Finally, we print the returned values to the console.

# create different arrays
arr1 = [1, 2, 3, 4, 5, nil]
arr2 = ["a", "b", "c", "d"]
arr3 = [true, false, nil]
arr4 = ["nil", "true", "false"]
arr5 = [nil, nil, nil]
arr6 = ["Python", "Java", nil, "JavaScript"]
# remove nil values with compact() method
a = arr1.compact()
b = arr2.compact()
c = arr3.compact()
d = arr4.compact()
e = arr5.compact()
f = arr6.compact()
puts "#{arr1}.compact() = #{a}"
puts "#{arr2}.compact() = #{b}"
puts "#{arr3}.compact() = #{c}"
puts "#{arr4}.compact() = #{d}"
puts "#{arr5}.compact() = #{e}"
puts "#{arr6}.compact() = #{f}"

Free Resources