Removing all nil elements from an array using compact! method

The compact! method removes all nil elements from the array permanently.

Syntax:

array.compact!

Example: In this example, we use compact! method to remove all occurrences of nil elements in the array permanently.

Ruby
# Define an array with nil elements
array = [1, nil, 3, nil, 5, nil]

# Remove all nil elements permanently using compact!
array.compact!

# Output the modified array
puts array.inspect  # Output: [1, 3, 5]

Output
[1, 3, 5]

How to remove all nil elements from an Array in Ruby permanently?

In this article, we will discuss how to remove all nil elements from an array permanently in Ruby. We can remove all nil elements from an array permanently through different methods ranging from using compact! method to delete method with nil argument.

Table of Content

  • Removing all nil elements from an array using compact! method
  • Removing all nil elements from an array using reject! method with nil? condition
  • Removing all nil elements from an array using delete method with nil argument

Similar Reads

Removing all nil elements from an array using compact! method

The compact! method removes all nil elements from the array permanently....

Removing all nil elements from an array using reject! method with nil? condition

The reject! method removes all elements that satisfy the nil? condition permanently....

Removing all nil elements from an array using delete method with nil argument

Delete method removes all occurrences of the specified value (nil in this case) from the array permanently....

Contact Us