Home > Ruby Notes > Enumeration over an array that is modified

Enumeration over an array that is modified

Tags:  

 
What happens if the target of #each is modified?

Test code:

 i = 0
 arr = [0]
 arr.each { |e|
   if i < 10
     arr << i+1
   end
   i+=1
 }
 puts arr

Result:

0
1
2
3
4
5
6
7
8
9
10

Conclusion:

#each probably remembers the position in the array.  It will cover the newly appended elements.



 RSS of this page