具有以下内容:
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 }
获得此结果的最合适方法是什么?
答案 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]}