I was looking at this problem on Stack Overflow (this one:
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"=>[#<struct Product name="Navel", category="Orange">],
"Apple"=>
[#<struct Product name="Golden Delicious", category="Apple">,
#<struct Product name="Granny Smith", category="Apple">]}
{}
{"Orange"=>[#<struct Product name="Navel", category="Orange">],
"Apple"=>
[#<struct Product name="Golden Delicious", category="Apple">,
#<struct Product name="Granny Smith", category="Apple">]}
My question: why is bar empty?
···
--
Glenn Jackman
Write a wise saying and your name will live forever. -- Anonymous