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

O

Onion Knight

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.
 
O

Onion Knight

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top