Russell
Russell

Reputation: 2812

Why deleting elements from a list in ruby does not work inside a for loop?

some_list = ['a', 'b', 'c']

for l in some_list
  some_list.delete_at(some_list.index(l))
end

puts some_list.inspect

It turns out, that at the end of the execution some_list is equal to ["b"]. Shouldn't it delete everything?

Upvotes: 2

Views: 1460

Answers (3)

glenn mcdonald
glenn mcdonald

Reputation: 15488

If you absolutely have to delete while iterating, iterate in reverse so you're changing the array behind your iteration instead of ahead of it. But like the others said, in this case you probably shouldn't be looping in the first place.

Upvotes: 2

Evan Jacobs
Evan Jacobs

Reputation: 23

There are several ways to delete elements from a list in Ruby which are easier and safer than iterating through that list.

For example,

colors = ["red", "green", "blue"]

# delete named elements
colors.delete("red")
=> ["green", "blue"]

# find difference in list and assign back to list
colors = colors - colors
=> []

Upvotes: 2

muirbot
muirbot

Reputation: 2081

In the first loop, l is at index 0, and 'a' gets deleted.

Then it loops again, and l is at index 1, which is now 'c' ('a' was deleted, remember?). It deletes 'c' and is done :)

Upvotes: 8

Related Questions