How to merge two hashes that have same keys in ruby

前端 未结 2 1951
感情败类
感情败类 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:39

    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) }
    
    

提交回复
热议问题