简体   繁体   中英

How to merge two hashes that have same keys in ruby

I have a two hashes that should have same keys like:

a = {a: 1, b: 2, c: 3}
b = {a: 2, b: 3, c: 4}

And I want to sum up each values like this:

if a.keys == b.keys
  a.values.zip(b.values).map{|a, b| a+b}
end

But this code doesn't work if the order of keys are different like b = {a: 2, c: 4, b: 3} .

How can I write the code taking into account about order of keys?

Use Hash#merge or Hash#merge! :

a = {a: 1, b: 2, c: 3}
b = {a: 2, c: 4, b: 3}
a.merge!(b) { |k, o, n| o + n }
a # => {:a=>3, :b=>5, :c=>7}

The block is called with key, old value, new value. And the return value of the block is used as a new value.

If you're using Active Support (Rails), which adds Hash#transform_values , I really like this easy-to-read solution when you have n hashes:

hashes = [hash_1, hash_2, hash_3] # any number of hashes
hashes.flat_map(&:to_a).group_by(&:first).transform_values { |x| x.sum(&:last) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM