From: Glenn Jackman Date: 2009-09-12T04:26:58+09:00 Subject: Re: populating a hash from an array using inject At 2009-09-11 02:07PM, "7stud --" wrote: > Glenn Jackman wrote: > > While I thank you for takking the time, I can't say I'm enlightened by > > your explanation. What's the real difference between the blocks > > > > bar = products.inject(Hash.new([])) {|h,p| h[p.category] << p; h} > > baz = products.inject(Hash.new([])) {|h,p| h[p.category] += [p]; h} > > > > Is it because += explicitly assigns a new object to the hash key? > > Yes. When the key doesn't exist the first line is equivalent to: > > bar = products.inject(Hash.new([])) {|h,p| [] << p; h} > > which does nothing to the hash--all it does is append p to an empty > array, and then the empty array is discarded. As we've seen, it's not discarded: it's kept for h's reference: products = [[1,2],[3,4],[1,5]] foo = products.inject(Hash.new([])) {|h,(a,b)| h[a] << b; h} # => {} foo[:unknown] # => [2, 4, 5] -- Glenn Jackman Write a wise saying and your name will live forever. -- Anonymous