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
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]
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.
Syntax:
array.reject!(&:nil?)
Example: In this example we use reject! method with nil? condition to removes all occurrence of nil element in the array permanently.
# Define an array with nil elements
array = [1, nil, 3, nil, 5, nil]
# Remove all nil elements permanently using reject!
array.reject!(&:nil?)
# Output the modified array
puts array.inspect # Output: [1, 3, 5]
Output
[1, 3, 5]
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.
Syntax:
array.delete(nil)
Example: In this example we use delete
method with nil
argument to removes all occurrence of nil element in the array permanently.
# Define an array with nil elements
array = [1, nil, 3, nil, 5, nil]
# Remove all nil elements permanently using delete
array.delete(nil)
# Output the modified array
puts array.inspect # Output: [1, 3, 5]
Output
[1, 3, 5]
Contact Us