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

**URL:** <https://www.ruby-forum.com/t/array-each-safe-when-modifying-its-elements/87681>\
**Category:** Ruby\
**Created:** [March 5, 2007, 4:10am UTC](https://www.ruby-forum.com/t/array-each-safe-when-modifying-its-elements/87681 "2007-03-05T04:10:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![onionknight](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/cc9497/32.png) [@onionknight](https://www.ruby-forum.com/u/onionknight)\
**Post date:** [March 5, 2007, 4:10am UTC](https://www.ruby-forum.com/t/array-each-safe-when-modifying-its-elements/87681/1 "2007-03-05T04:10:57Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![onionknight](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/cc9497/32.png) [@onionknight](https://www.ruby-forum.com/u/onionknight)\
**Post date:** [March 5, 2007, 4:17am UTC](https://www.ruby-forum.com/t/array-each-safe-when-modifying-its-elements/87681/2 "2007-03-05T04:17:05Z")

</div>

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.
