Carl Markham Carl Markham - 3 months ago 9
Ruby Question

Merge hashes with value

Say I have the following array of hashes

[
{
created: '11/11/86',
amount: 10,
},
{
created: '11/11/86',
amount: 20,
},
{
created: '12/11/86',
amount: 4,
}
]


I want to merge all hashes with the same
created
key so the result would be:

[
{
created: '11/11/86',
amount: 30,
},
{
created: '12/11/86',
amount: 4,
}
]


I realise I can use loops but I am looking for something more elegant.

The hashes could have more keys, but I only care about these 2.

Answer

You can try with map and sum (since you are using rails):

arr.group_by{|x| x[:created]}.map{|date, x|
  {
    created: date,
    amount: x.sum{|xx| xx[:amount]}
  } 
}

# => {:created=>"11/11/86", :amount=>30}, {:created=>"12/11/86", :amount=>4}]
Comments