Remove an element from an array in Ruby
August 18, 2022 ‐ 1 min read
In Ruby we have multiple options for removing an element from an array. If we wish to do so by matching a given value we can use reject!
or delete_if
. This removes all the matching values from the array.
toppings = [
'mozzarella',
'tomato',
'salami',
'pineapple'
]
toppings.reject! { |n| n == 'pineapple' }
puts toppings.inspect
#=> ["mozzarella", "tomato", "salami"]