Search code examples
rubyarrayshashenumerable

Convert Array to Hash removing duplicate keys and adding values at the same time


I have an array that looks like so:

f = [["Wed, 12-31", 120.0],["Thu, 01-01", 120.0], ["Thu, 01-01", 120.0]]

I can convert it to a hash and remove the duplicate keys:

h = Hash[ *f.collect { |v| [v] }.flatten ]
# => {"Wed, 12-31"=>120.0, "Thu, 01-01"=>120.0}

which is almost there, but I'd like to sum the value for elements with the identical date strings, the desired result from the above array would be this:

{"Wed, 12-31"=>120.0, "Thu, 01-01"=>240.0}

How can I accomplish this?


Solution

  • This works:

    result = Hash.new(0)
    f = [["Wed, 12-31", 120.0],["Thu, 01-01", 120.0], ["Thu, 01-01", 120.0]]
    f.each { |subarray| result[subarray[0]] += subarray[1] }
    puts result
    

    If you would like to be fancy you could use .inject()