Clean solution to this ruby iterator trickiness?

Posted by mstksg on Stack Overflow See other posts from Stack Overflow or by mstksg
Published on 2010-06-09T03:41:15Z Indexed on 2010/06/09 3:42 UTC
Read the original article Hit count: 185

Filed under:
|
|
|
|
k = [1,2,3,4,5]
for n in k
  puts n
  if n == 2
    k.delete(n)
  end
end
puts k.join(",")

# Result:
# 1
# 2
# 4
# 5
# [1,3,4,5]

# Desired:
# 1
# 2
# 3
# 4
# 5
# [1,3,4,5]

This same effect happens with the other array iterator, k.each:

k = [1,2,3,4,5]
k.each do |n|
  puts n
  if n == 2
    k.delete(n)
  end
end
puts k.join(",")

has the same output.

The reason this is happening is pretty clear...Ruby doesn't actually iterate through the objects stored in the array, but rather just turns it into a pretty array index iterator, starting at index 0 and each time increasing the index until it's over. But when you delete an item, it still increments the index, so it doesn't evaluate the same index twice, which I want it to.

This might not be what's happening, but it's the best I can think of.

Is there a clean way to do this? Is there already a built-in iterator that can do this? Or will I have to dirty it up and do an array index iterator, and not increment when the item is deleted?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about array