我想总结相同键的值,如
arr = [{"69120090" => [1, 2, 3]}, {"69120090" => [4, 5, 6]}]
我需要导致:
result = [{"69120090" => [5, 7, 9]}]
Hash#merge!
用块减少:
arr = [{"69120090"=> [1, 2, 3] }, {"69120090"=> [4, 5, 6] }]
arr.each_with_object({}) do |h, acc|
acc.merge!(h) { |_, v1, v2| v1.zip(v2).map(&:sum) }
end
#⇒ {"69120090"=>[5, 7, 9]}
上面接受任意数量的散列,每个散列具有任意数量的键。
只是为了有另一个选项,给定数组:
arr = [{ a: [1, 2, 3], b:[8,9,0] }, { a: [4, 5, 6], c: [1,2,3] }, { b: [0,1,2], c: [1,2,3] } ]
你可以写:
tmp = Hash.new{ |k,v| k[v] = [] }
arr.each { |h| h.each { |k,v| tmp[k] << v } }
tmp.transform_values { |k| k.transpose.map(&:sum) }
哪个回报
tmp #=> {:a=>[5, 7, 9], :b=>[8, 10, 2], :c=>[2, 4, 6]}
(arr.each_with_object(Hash.new{ |k,v| k[v] = [] }) { |h, tmp| h.each { |k,v| tmp[k] << v } }).transform_values { |k| k.transpose.map(&:sum) }