Sum 2 hashes attributes with the same key

12,385

Solution 1

a_hash = {'a' => 30, 'b' => 14}
b_hash = {'a' => 4, 'b' => 23, 'c' => 7}

a_hash.merge(b_hash){ |k, a_value, b_value| a_value + b_value }
=> {"a"=>34, "b"=>37, "c"=>7}

b_hash.merge(a_hash){ |k, b_value, a_value| a_value + b_value }
=> {"a"=>34, "b"=>37, "c"=>7}

Solution 2

If some one looking to add more than 2 hashes, use this

#sample array with any number of hashes
sample_arr =  [{:a=>2, :b=>4, :c=>8, :d=>20, :e=>5},
{:a=>1, :b=>2, :c=>4, :d=>10, :e=>5, :r=>7},
{:a=>1, :b=>2, :c=>4, :d=>10},
{:a=>2, :b=>4, :c=>8, :d=>20, :e=>5},
{:a=>1, :b=>2, :c=>4, :d=>10, :e=>5, :r=>7},
{:a=>1, :b=>2, :c=>4, :d=>10}]

sample_arr.inject { |acc, next_obj| acc.merge(next_obj) { |key,arg1,arg2| arg1+arg2 } }
# => {:a=>8, :b=>16, :c=>32, :d=>80, :e=>20, :r=>14} 

In case of heterogeneous hash (containing both String and Number). For adding only integers.

@resultant_visit_hash = arr.inject { |acc, next_obj| acc.merge(next_obj) { |key,arg1,arg2| arg1+arg2 if (arg1.class == Integer && arg2.class == Integer) } } 

Code is self explanatory.

Share:
12,385
el_quick
Author by

el_quick

Just a developer more.

Updated on June 06, 2022

Comments

  • el_quick
    el_quick about 2 years

    I have 2 hashes, for example:

    {'a' => 30, 'b' => 14}
    {'a' => 4, 'b' => 23, 'c' => 7}
    

    where a, b and c are objects. How can I sum those hashes' keys to get a new hash like:

    {'a' => 34, 'b' => 37, 'c' => 7}
    
  • NAREN PUSHPARAJU
    NAREN PUSHPARAJU almost 5 years
    How to add only specific keys?