John Smith John Smith - 6 months ago 12
Ruby Question

How to sum up values in a nested array

I have an array in the following format:

arr = [
["OMAA002S16001006 1088", 13],
["OMAA002S16001006 1088", 13],
["OMAA002S16001006 1088", 10],
["OMRA001S16116037 1001", 10],
["OMRA001S16116037 0110", 9],
["OMAA002S16001014 0119", 9],
["OMAA002S16001002 0134", 9]
]


The first entries are the same code but with different numbers. What's the best way to make the entries unique and sum up the values on the right? The result should be like this:

[
["OMAA002S16001006 1088", 36],
["OMRA001S16116037 1001", 10],
["OMRA001S16116037 0110", 9],
["OMAA002S16001014 0119", 9],
["OMAA002S16001002 0134", 9]
]

Answer

Using Enumerable#each_with_object:

arr.each_with_object(Hash.new(0)) { |(k, v), h| h[k] += v }
#=> {"OMAA002S16001006 1088"=>36,
#    "OMRA001S16116037 1001"=>10,
#    "OMRA001S16116037 0110"=>9,
#    "OMAA002S16001014 0119"=>9,
#    "OMAA002S16001002 0134"=>9}

You can call to_a to convert it back to an array.