How can I use Array#delete while iterating over the array?

Adrian picture Adrian · Jul 16, 2010 · Viewed 44.2k times · Source

I have an array that I want to iterate over and delete some of the elements. This doesn't work:

a = [1, 2, 3, 4, 5]
a.each do |x|
  next if x < 3
  a.delete x
  # do something with x
end
a #=> [1, 2, 4]

I want a to be [1, 2]. How can I get around this?

Answer

Chubas picture Chubas · Jul 16, 2010

a.delete_if { |x| x >= 3 }

See method documentation here

Update:

You can handle x in the block:

a.delete_if do |element|
  if element >= 3
    do_something_with(element)
    true # Make sure the if statement returns true, so it gets marked for deletion
  end
end