HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Merging hashes, summing values that have the same key

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
samethemergingsummingthathashesvalueshavekey

Problem

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' => 153, '212' => 153}, {'212' => 1}]


When I run

process_codes_and_totals(codes_and_totals)

Then the return value should be

=> {'1001' => 153, '212' => 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

Solution

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).

Code Snippets

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

Context

StackExchange Code Review Q#136543, answer score: 5

Revisions (0)

No revisions yet.