来自具有相同键的两个不同对象的ruby / merge-sum值

时间:2019-05-17 17:05:41

标签: ruby hash sum

具有以下内容:

a = { k1: 10, k2: 20 }
b = { k1: 14, k2: 10 }

我需要得到:

# Not sure if that's the right approach, but broken down in steps :

# c = { k1: a[k1] + b[k1], k2: a[k2] + b[k2] }
# c = { k1: 10 + 14, k2: 20 + 10 }
c = { k1: 24, k2: 30 }

获得此结果的最合适方法是什么?

2 个答案:

答案 0 :(得分:6)

“Also, using the “=” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a “/” request happens frequently, defining “location = /” will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations.”

这使用Hash#merge的形式,该形式采用了块a.merge(b) { |_,o,n| o+n } #=> {:k1=>24, :k2=>30} 确定合并的两个哈希中存在的键值(块变量{ |_,o,n| o+n })。有关块变量_o的说明,请参阅文档。

答案 1 :(得分:0)

第一个答案更好,但这也可以。

a = { k1: 10, k2: 20 }
b = { k1: 14, k2: 10 }
c = {}
keys = (a.keys + b.keys).uniq
keys.each {|k| c[k] = a[k] + b[k]}