简体   繁体   English

在哈希数组中添加相同Key的值

[英]Add values of same Key in array of hashes

Trying to add values of same key but with iterating it. 尝试添加相同键的值,但要对其进行迭代。 here is my array 这是我的数组

arr = [ {a: 10, b: 5, c: 2}, {a: 5, c: 3}, { b: 15, c: 4}, {a: 2}, {} ]

Want to converted it like 想将其转换为

{a: 17, b: 20, c: 9} 

Here is one way to do this by making use of Enumerable#reduce and Hash#merge : 这是通过使用Enumerable#reduceHash#merge做到这一点的一种方法:

arr.reduce {|acc, h| acc.merge(h) {|_,v1,v2| v1 + v2 }}
#=> {:a=>17, :b=>20, :c=>9}

each_with_object to the rescue: each_with_object进行救援:

result = arr.each_with_object(Hash.new(0)) do |hash, result|
  hash.each { |key, value| result[key] += value}
end

p result

#1 Use a "counting hash" #1使用“计数哈希”

Edit: I just noticed that @Pascal posted the same solution earlier. 编辑:我只是注意到@Pascal早些时候发布了相同的解决方案。 I'll leave mine for the explanation. 我将离开我的解释。

arr.each_with_object(Hash.new(0)) { |h,g| h.each { |k,v| g[k] += v } }
  #=> {:a=>17, :b=>20, :c=>9} 

h = Hash.new(0) is a counting hash with a default value of zero. h = Hash.new(0)是默认值为零的计数哈希。 That means that if h does not have a key k , h[k] returns zero (but the hash is not altered). 这意味着,如果h没有键k ,则h[k]返回零(但哈希值不会改变)。 Ruby expands h[k] += 4 to h[k] = h[k] + 4 , so if h does not have a key k , h[k] on the right side of the equality equals zero. Ruby将h[k] += 4扩展为h[k] = h[k] + 4 ,因此,如果h没有键k ,则等式右侧的h[k]等于零。

#2 Use Hash#update #2使用哈希值#update

Specifically, use the form of this method (aka merge! ) that employs a block to determine the values of keys that are present in both hashes being merged. 具体来说,使用此方法的形式(也称为merge! ),该方法采用一个块来确定要合并的两个哈希中都存在的键的值。

arr.each_with_object({}) { |h,g| g.update(h) { |_,o,n| o+n } }
  #=> {:a=>17, :b=>20, :c=>9} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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