Reputation:
I have an array of Products
, each of which has a name and a category. I would like to produce a hash in which each key is a category string and each element is a product with that category, akin to the following:
{ "Apple" => [ <Golden Delicious>, <Granny Smith> ], ...
"Banana" => ...
Is this possible?
Upvotes: 4
Views: 2299
Reputation: 2179
The oneliner
arr = [["apple", "granny"],["apple", "smith"], ["banana", "chiq"]]
h = arr.inject(Hash.new {|h,k| h[k]=[]}) {|ha,(cat,name)| ha[cat] << name; ha}
:-)
But I agree, #group_by is much more elegant.
Upvotes: 1
Reputation: 49354
# a for all
# p for product
new_array = products.inject({}) {|a,p| a[p.category.name] ||= []; a[p.category.name] << p}
Upvotes: 0
Reputation: 370357
In 1.8.7+ or with active_support (or facets, I think), you can use group_by:
products.group_by {|prod| prod.category}
Upvotes: 8
Reputation: 12346
h = Hash.new {|h, k| h[k] = []}
products.each {|p| h[p.category] << p}
Upvotes: 3