ruby remove nil element in array
Ruby: Removing nil Elements from an Array
To remove nil
elements from an array in Ruby, you can use the compact
method. The compact
method removes all nil
elements from the array and returns a new array without those elements. Here's how you can do it:
array = [1, nil, 2, nil, 3, nil]
new_array = array.compact
In this example, new_array
will contain [1, 2, 3]
, without the nil
elements.
Let's break down the steps:
Create an array with
nil
elements:ruby array = [1, nil, 2, nil, 3, nil]
Use the
compact
method to removenil
elements and assign the result to a new array:ruby new_array = array.compact
The compact
method removes all nil
elements from the array
and returns a new array without those elements.
- The resulting
new_array
will contain only the non-nil elements:ruby puts new_array # Output: [1, 2, 3]
The new_array
will contain [1, 2, 3]
, without the nil
elements.
That's how you can remove nil
elements from an array in Ruby using the compact
method.