From: Johan Veenstra Date: 2006-01-29T22:06:24+09:00 Subject: Re: Loop weirdness ------=_Part_8062_25616106.1138539971312 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline Hmm interesting, I've added line number, couldn't explain it other wise: def categorise(items) 1 categorised =3D [] 2 add =3D proc { |item| categorised << { :num =3D> item[:num], :items =3D= > [ 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] =3D=3D item[:num] 9 cat[:items] << item[:foo] 10 break 11 elsif cat =3D=3D categorised.last 12 add.call(item) 13 end 14 end 15 end 16 end 17 categorised end p categorise( [ { :num =3D> 1, :foo =3D> 'foo1' }, { :num =3D> 45, :foo =3D= > 'foo45' } ] ) 1: categorised =3D [] 3: first item( item[:num] =3D=3D 1 ) 4: categorised is empty 5: {:num=3D>1, :items=3D>["foo1"]} is added to categorised, so far so good 3: next item( item[:num] =3D 45 ) 4: categorised is not empty 7: first category (cat[:num] =3D=3D 1) 8: item[:num] is not equal to cat[:num] (45 !=3D 1 ) 11: cat is last category 12: { :num =3D> 45, :foo =3D> ['foo45'] } is added to categorised, just wha= t we need 7: next category (yes there is a next category, number 45 that we've just added a moment ago) ( cat[:num] =3D=3D 45) 8: added ['foo45'] to category 45, oh boy 10:break 3: no more items 18: return categorised ------=_Part_8062_25616106.1138539971312--