From: Jonathan Leighton Date: 2006-01-29T22:39:26+09:00 Subject: Re: Loop weirdness Okay, so let me get this right... if you do foo.each { } foo is re-evaluated with each iteration? Hence the bug? Why? Jon On Sun, 2006-01-29 at 22:06 +0900, Johan Veenstra wrote: > Hmm interesting, I've added line number, couldn't explain it other wise: > > def categorise(items) > 1 categorised = [] > 2 add = proc { |item| categorised << { :num => item[:num], :items => [ > item[:foo] ] } } > 3 items.each do |item| > 4 if categorised.empty? > 5 add.call(item) > 6 else > 7 categorised.each do |cat| > 8 if cat[:num] == item[:num] > 9 cat[:items] << item[:foo] > 10 break > 11 elsif cat == categorised.last > 12 add.call(item) > 13 end > 14 end > 15 end > 16 end > 17 categorised > end > > p categorise( [ { :num => 1, :foo => 'foo1' }, { :num => 45, :foo => 'foo45' > } ] ) > > 1: categorised = [] > 3: first item( item[:num] == 1 ) > 4: categorised is empty > 5: {:num=>1, :items=>["foo1"]} is added to categorised, so far so good > 3: next item( item[:num] = 45 ) > 4: categorised is not empty > 7: first category (cat[:num] == 1) > 8: item[:num] is not equal to cat[:num] (45 != 1 ) > 11: cat is last category > 12: { :num => 45, :foo => ['foo45'] } is added to categorised, just what we > need > 7: next category (yes there is a next category, number 45 that we've just > added a moment ago) ( cat[:num] == 45) > 8: added ['foo45'] to category 45, oh boy > 10:break > 3: no more items > 18: return categorised -- Jonathan Leighton http://turnipspatch.com/ | http://jonathanleighton.com/ | http://digital-proof.org/