Merging hashes, summing values that have the same key I'm trying to group by keys in an Array of Hashes in the following form and add their totals. Maybe with #map and #reduce/#inject. I know there is a more compact way to do this.

Given I have

codes_and_totals = [{'1001' =&gt; 153, '212' =&gt; 153}, {'212' =&gt; 1}]


When I run 

process_codes_and_totals(codes_and_totals)

Then the return value should be

=&gt; {'1001' =&gt; 153, '212' =&gt; 154}

Currently #process_codes_and_totals looks like this

def process_codes_and_totals(codes_and_totals)
    totals_across_locations = {}
    codes_and_totals.each do |location|
      location.each do |class_code, total|
        totals_across_locations[class_code] ||= 0
        totals_across_locations[class_code] += total
      end
    end

    totals_across_locations
end
One way might be to use #reduce (as you suggest) and Hash#merge with a block:

totals = codes_and_totals.reduce({}) do |sums, location|
  sums.merge(location) { |_, a, b| a + b }
end


The merge-block is only invoked if a key exists in both the hashes being merged, so we don't need to guard against nil or start with a zero value. If the block runs, it's because there are two number values that need to be merged (i.e. added, in this case).