Add values of same Key in array of hashes

2019-07-26 17:08发布

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} 

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-26 17:23

each_with_object to the rescue:

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

p result
查看更多
三岁会撩人
3楼-- · 2019-07-26 17:25

Here is one way to do this by making use of Enumerable#reduce and Hash#merge:

arr.reduce {|acc, h| acc.merge(h) {|_,v1,v2| v1 + v2 }}
#=> {:a=>17, :b=>20, :c=>9}
查看更多
贼婆χ
4楼-- · 2019-07-26 17:45

#1 Use a "counting hash"

Edit: I just noticed that @Pascal posted the same solution earlier. 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. That means that if h does not have a key k, h[k] returns zero (but the hash is not altered). 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.

#2 Use Hash#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.

arr.each_with_object({}) { |h,g| g.update(h) { |_,o,n| o+n } }
  #=> {:a=>17, :b=>20, :c=>9} 
查看更多
登录 后发表回答