From: "David A. Black" Date: 2009-02-16T00:22:30+09:00 Subject: Re: Iterating a changing Hash under 1.9.1 Hi -- On Sun, 15 Feb 2009, Phrogz wrote: > The following code shows that Hash#each under 1.9.1p0 does not iterate > over keys added during iteration: > a = [ 1, 2, 3 ]; h = { 0=>0 } > h.each{ |k,v| h[a[k]] = a[k] } > p h > #=> {0=>0, 1=>1} > > However, this code (on 1.9.1p0) results in a ruby process with > unending 100% CPU usage, presumably due to an unending loop that keeps > traversing newly-added items: > h = { 1=>nil, 2=>nil } > h.each{ |k,v| h.delete(k); h[k]=v } > (Credit to "tama" for posting this on the ramaze group.) > > I'm assuming that one of these two are a bug, since they seem > contradictory. I'd like to think that the latter behavior is the bug, > and that hashes aren't supposed to iterate over keys added or moved > during iteration. Can anyone confirm or deny this? I can only add what I think is another interesting example: h = {1,2,3,4} h.select {|k,v| h[rand] = 1 v > 4 } This exits in 1.8 but goes on forever in 1.9. I'm not sure whether it's because of the override that Hash#select does of Enumerable#select. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!