From: Glenn Jackman Date: 2009-09-11T08:30:07+09:00 Subject: populating a hash from an array using inject I was looking at this problem on Stack Overflow (this one: http://stackoverflow.com/questions/1405657/reorganizing-ruby-array-into-hash The question is how to "convert" an array of objects into a hash. Consider this code: require 'pp' p RUBY_VERSION Product = Struct.new(:name, :category) products = [ ['Apple','Golden Delicious'], ['Apple','Granny Smith'], ['Orange','Navel'] ].collect {|cat, name| Product.new(name, cat)} foo = products.inject({}) {|h,p| h[p.category] ||= []; h[p.category] << p; h} pp foo bar = products.inject(Hash.new([])) {|h,p| h[p.category] << p; h} pp bar baz = products.inject(Hash.new([])) {|h,p| h[p.category] += p; h} pp baz It outputs: "1.8.7" {"Orange"=>[#], "Apple"=> [#, #]} {} {"Orange"=>[#], "Apple"=> [#, #]} My question: why is bar empty? -- Glenn Jackman Write a wise saying and your name will live forever. -- Anonymous