我需要基于键对每个哈希行的值求和。
在下面的示例中,我需要将A与A,B与B,C与C,D与D的所有行相加,最后返回具有完整值的单个哈希。
{adv=>{:a=>10, :b=>180, :c=>30, :d=>15}}
{adv=>{:a=>15, :b=>120, :c=>60, :d=>100}}
{adv=>{:a=>20, :b=>120, :c=>90, :d=>25}}
答案 0 :(得分:0)
list = [
{:adv=>{:a=>10, :b=>180, :c=>30, :d=>15}},
{:adv=>{:a=>15, :b=>120, :c=>60, :d=>100}},
{:adv=>{:a=>20, :b=>120, :c=>90, :d=>25}}
]
result = list.reduce do |memo, hsh|
{
adv: memo[:adv].merge(hsh[:adv]) do |key, val1, val2|
val1 + val2
end
}
end
puts result
# => {:adv=>{:a=>45, :b=>420, :c=>180, :d=>140}}