I am attempting to combine two hashes together, and am having trouble figuring out the best method to do it. I feel like there must be an easy way to do it with enumerables...
I'd like to turn this:
[{ id: 5, count: 10 }, { id: 6, count: -3 }, { id: 5, count: -2 }, { id: 3, count: 4}]
into this:
[{ id: 5, count: 8 }, { id: 6, count: -3 }, { id: 3, count: 4}]
So that hashes with the same "id" are summed together. Anyone have any ideas on how to quickly do this?
I tried Hash.merge but that didn't work correctly...
Here is a way :
hash = [{ id: 5, count: 10 }, { id: 6, count: -3 }, { id: 5, count: -2 }, { id: 3, count: 4}]
merged_hash = hash.group_by { |h| h[:id] }.map do |_,v|
v.reduce do |h1,h2|
h1.merge(h2) { |k,o,n| k == :count ? o + n : o }
end
end
merged_hash
# => [{:id=>5, :count=>8}, {:id=>6, :count=>-3}, {:id=>3, :count=>4}]
Look at these methods Hash#merge
, Enumerable#reduce
and Enumerable#group_by
.