How to merge two hashes that have same keys in ruby

前端 未结 2 1954
感情败类
感情败类 2021-02-19 02:26

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:<

2条回答
  •  孤独总比滥情好
    2021-02-19 02:49

    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.

提交回复
热议问题