From: Ehsanul Hoque Date: 2009-09-11T09:07:37+09:00 Subject: Re: populating a hash from an array using inject --_469c289c-66dc-4634-b3ef-b8d7701a9ecc_ Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable I don't have an answer=2C but trying out the code in JRuby=2C I can see tha= t the default value for bar becomes simply the products array after the inj= ect() method is used. One more thing that requires an explanation. You can = see this by appending this line to your code: pp bar["random string here"] > Date: Fri=2C 11 Sep 2009 08:30:07 +0900 > From: glennj@ncf.ca > Subject: populating a hash from an array using inject > To: ruby-talk@ruby-lang.org >=20 > I was looking at this problem on Stack Overflow (this one: > http://stackoverflow.com/questions/1405657/reorganizing-ruby-array-into-h= ash >=20 > The question is how to "convert" an array of objects into a hash. >=20 > Consider this code: >=20 > require 'pp' > p RUBY_VERSION >=20 > Product =3D Struct.new(:name=2C :category) > products =3D [ > ['Apple'=2C'Golden Delicious']=2C > ['Apple'=2C'Granny Smith']=2C > ['Orange'=2C'Navel'] > ].collect {|cat=2C name| Product.new(name=2C cat)} >=20 > foo =3D products.inject({}) {|h=2Cp| h[p.category] ||=3D []=3B h[p.ca= tegory] << p=3B h} > pp foo >=20 > bar =3D products.inject(Hash.new([])) {|h=2Cp| h[p.category] << p=3B = h} > pp bar >=20 > baz =3D products.inject(Hash.new([])) {|h=2Cp| h[p.category] +=3D p= =3B h} > pp baz >=20 > It outputs: >=20 > "1.8.7" > {"Orange"=3D>[#= ]=2C > "Apple"=3D> > [#= =2C > #]} > {} > {"Orange"=3D>[#= ]=2C > "Apple"=3D> > [#= =2C > #]} >=20 > My question: why is bar empty? >=20 > --=20 > Glenn Jackman > Write a wise saying and your name will live forever. -- Anonymous >=20 _________________________________________________________________ Windows Live: Make it easier for your friends to see what you=92re up to on= Facebook. http://windowslive.com/Campaign/SocialNetworking?ocid=3DPID23285::T:WLMTAGL= :ON:WL:en-US:SI_SB_facebook:082009= --_469c289c-66dc-4634-b3ef-b8d7701a9ecc_--