From: 7stud -- Date: 2009-09-12T06:25:25+09:00 Subject: Re: populating a hash from an array using inject Glenn Jackman wrote: > At 2009-09-11 02:07PM, "7stud --" wrote: >> >> 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] ...and this is a lie too: > If you access a non-existent key, say h["A"], then that line is > equivalent to > baz = products.inject(Hash.new([])) {|h,p| h["A"] = [] + [p]; h} You asked for lies. I gave them to you. -- Posted via http://www.ruby-forum.com/.