What is the compact method in Ruby?

Overview

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.

Syntax

array.compact

Parameters

It does not take any parameters. It can only be used with an array.

Return value

This method returns an array containing non-nil elements.

Code example

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 arrays
arr1 = [1, nil, 2, nil, 3]
arr2 = ["a", "b", "c", "d"]
arr3 = [true, false, nil]
arr4 = ["Meta", "Apple", "nill",nil]
# Call the compact method
a = arr1.compact
b = arr2.compact
c = arr3.compact
d = arr4.compact
# Print the returned values
puts "#{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.

Explanation

  • In lines 2 to 5, we create arrays with nil elements.
  • In lines 8 to 11, we call the compact method on the arrays.
  • In lines 14 to 17, we display the results.