locoboy locoboy - 6 months ago 27
Ruby Question

How to condense summable metrics to a unique identifier in a ruby table

I'm trying to condense summable metrics to a unique identifier in a ruby table.

I have the following table:

[["id1", 123], ["id2", 234], ["id1", 345]]


What's the most effective way to condense the metrics such that it will look like this:

[["id1", 468], ["id2", 234]]

Answer

I think the other answerers are overthinking this. You can do this with just one operation, each_with_object, and a Hash:

metrics = [["id1", 123], ["id2", 234], ["id1", 345]]

metrics.each_with_object(Hash.new(0)) do |(id, val), sums|
  sums[id] += val
end
# => {"id1"=>468, "id2"=>234}

If you want an Array instead of a Hash at the end just call to_a on the result, but there are few compelling reasons to do so.