Array#each, safe when modifying it's elements?

Will Array#each only go through each unique element once even if you
were to throw around the elements in the array or will it just take
whatever element is after the current one?
I tried it myself but it behaves a bit strange.

a = [1, 2, 3, 4, 5, 6, 7]
a.each do |x|
print x
if x == 2
a.reverse!
end
end

It prints 1254327. Somehow the last element was intact and printed a 7
instead of 1.

No wait I’m dumb, there’s a second 2 at the end so the array get
reversed again. I guess it proves it isn’t intact though. To solve that
I’m thinking that I could just copy the array and use that copy for
iteration.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs