49

I have an array of hashes:

[{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3>}, {"Dry Goods"=>2}]

I need to use inject here I think but I've really been struggling.

I want a new hash that reflects the sum of the previous hash's duplicate keys:

[{"Vegetable"=>15}, {"Dry Goods"=>5}]

I'm in control of the code that outputs this hash so I can modify it if necessary. The results were mainly hashes because this could end up nested any number of levels deep and then it's easy to call flatten on the array but not flatten the keys/values of the hash too:

def recipe_pl(parent_percentage=nil)
  ingredients.collect do |i|

    recipe_total = i.recipe.recipeable.total_cost 
    recipe_percentage = i.ingredient_cost / recipe_total

    if i.ingredientable.is_a?(Purchaseitem)
      if parent_percentage.nil?
        {i.ingredientable.plclass => recipe_percentage}
      else
        sub_percentage = recipe_percentage * parent_percentage
        {i.ingredientable.plclass => sub_percentage}
      end
    else
      i.ingredientable.recipe_pl(recipe_percentage)
    end
  end
end 
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
blastula
  • 637
  • 1
  • 6
  • 10

5 Answers5

96
ar = [{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3}, {"Dry Goods"=>2}]
p ar.inject{|memo, el| memo.merge( el ){|k, old_v, new_v| old_v + new_v}}
#=> {"Vegetable"=>15, "Dry Goods"=>5}

Hash.merge with a block runs the block when it finds a duplicate; inject without a initial memo treats the first element of the array as memo, which is fine here.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • 1
    Thanks, this answers the question and I did not know that about merge. Much appreciated. – blastula Dec 15 '10 at 19:58
  • 2
    +1 This is one of those jewels that needs to be in the Ruby books, but isn't. – the Tin Man Dec 16 '10 at 04:02
  • could you explain the naming here, what does memo and el mean? – appleLover Apr 06 '14 at 22:04
  • 1
    @appleLover `memo` and `el` don't mean anything, you could exchange them with any word. They are variable names; I chose these for `memo =>I remember, el => element` – steenslag Apr 06 '14 at 22:31
  • Can u please help me understand this code, please mention the values for k, old_v, new_v. I got confused – RubyMiner Nov 09 '15 at 14:08
  • `{|k, old_v, new_v| old_v + new_v}` runs only when the hash already has a certain key (with a value: old_val). The key ("Vegeteable" and the old_value (10) and the new_value (5) are send to the block; the result of the block is then stored as the value (15) for that key. – steenslag Nov 09 '15 at 19:52
  • How might this be used to merge values rather than keys? For example if my array contains: `[{"Vegetable"=>10,"Department"=>"Produce"}, {"Fruit"=>20, "Department"=>"Produce"}]` If I wanted to get the total count of all items in the Produce department... – wrydere Jun 22 '17 at 16:28
  • If you need default values, you can change `inject` to `reduce` and define a starting hash. Example: `p ar.reduce({ "Other" => 0 }) { |memo, el| memo.merge(el){ |k, old_v, new_v| old_v + new_v } }` – Pedro Cavalheiro Jan 19 '18 at 18:06
  • +1 Thanks! This answer solved my problem to merge hashes using `a.merge(b) { |key, value_a, value_b | value_a + value_b }` – Christian Feb 02 '19 at 00:25
17

Simply use:

array = [{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3}, {"Dry Goods"=>2}]
array.inject{|a,b| a.merge(b){|_,x,y| x + y}}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user1922900
  • 1,087
  • 8
  • 4
12
ar = [{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3}, {"Dry Goods"=>2}]

While the Hash.merge technique works fine, I think it reads better with an inject:

ar.inject({}) { |memo, subhash| subhash.each { |prod, value| memo[prod] ||= 0 ; memo[prod] += value } ; memo }
=> {"Dry Goods"=>5, "Vegetable"=>15}

Better yet, if you use Hash.new with a default value of 0:

ar.inject(Hash.new(0)) { |memo, subhash| subhash.each { |prod, value| memo[prod] += value } ; memo }
=> {"Dry Goods"=>5, "Vegetable"=>15}

Or if inject makes your head hurt:

result = Hash.new(0)
ar.each { |subhash| subhash.each { |prod, value| result[prod] += value } }
result
=> {"Dry Goods"=>5, "Vegetable"=>15}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Head
  • 4,691
  • 3
  • 30
  • 18
4

If have two hashes with multiple keys:

h1 = { "Vegetable" => 10, "Dry Goods" => 2 }
h2 = { "Dry Goods" => 3, "Vegetable" => 5 }
details = {}
(h1.keys | h2.keys).each do |key|
  details[key] = h1[key].to_i + h2[key].to_i
end
details
TuteC
  • 4,342
  • 30
  • 40
4

I'm not sure that a hash is what you want here, because I don't multiple entries in each hash. so I'll start by changing your data representation a little.

ProductCount=Struct.new(:name,:count)
data = [ProductCount.new("Vegetable",10),
        ProductCount.new("Vegetable",5),
        ProductCount.new("Dry Goods",3),
        ProductCount.new("Dry Goods",2)]

If the hashes can have multiple key-value pairs, then what you probably want to do is

data = [{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3>}, {"Dry Goods"=>2}]
data = data.map{|h| h.map{|k,v| ProductCount.new(k,v)}}.flatten

Now use the facets gem as follows

require 'facets'
data.group_by(&:name).update_values{|x| x.map(&:count).sum}

The result is

{"Dry Goods"=>5, "Vegetable"=>15}
Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
  • Thank you! Structs I am aware of but need to really get my hands dirty with, facets was completely unknown to me. I have added the original code that outputs the hashes because I can probably do something simpler there. – blastula Dec 15 '10 at 18:55