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.
# 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
Contact Us