Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum 2 hashes attributes with the same key

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} 
like image 438
el_quick Avatar asked Nov 03 '10 20:11

el_quick


1 Answers

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} 
like image 113
Nakilon Avatar answered Sep 28 '22 15:09

Nakilon