Evan Baxter
Evan Baxter

Reputation:

Reorganizing Ruby array into hash

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

Answers (4)

Robert Klemme
Robert Klemme

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

Eimantas
Eimantas

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

sepp2k
sepp2k

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

Martin DeMello
Martin DeMello

Reputation: 12346

h = Hash.new {|h, k| h[k] = []}
products.each {|p| h[p.category] << p}

Upvotes: 3

Related Questions