[ACCEPTED]-Sum 2 hashes attributes with the same key-sum
Accepted answer
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}
0
If some one looking to add more than 2 hashes, use 3 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+agr2 } }`
In case of heterogeneous hash (containing 2 both String and Number). For adding only 1 integers.
@resultant_visit_hash = arr.inject { |acc, next_obj| acc.merge(next_obj) { |key,arg1,arg2| arg1+agr2 if (arg1.class == Fixnum && arg2.class == Fixnum) } }
Code is self explanatory.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.