Reputation: 703
My hash is:
{"20141113"=>[1], "20141114"=>[1, 1]}
I want to get:
{"20141113"=>[1], "20141114"=>[2]}
or
{"20141113"=>1, "20141114"=>2}
How do I do it?
Upvotes: 2
Views: 51
Reputation: 110645
Another way:
h = {"20141113"=>[1], "20141114"=>[1, 1]}
h.merge(h) { |*_,a| a.reduce(:+) }
#=> {"20141113"=>1, "20141114"=>2}
This uses the form of Hash#merge that takes a block.
Upvotes: 1
Reputation: 368894
Get key, sum pair:
h.map { |k, v| [k, v.reduce(:+)] }
# => [["20141113", 1], ["20141114", 2]]
And convert it to hash using Hash::[]
:
{"20141113"=>[1], "20141114"=>[1, 1]}
Hash[h.map { |k, v| [k, v.reduce(:+)]}]
# => {"20141113"=>1, "20141114"=>2}
Or Enumerable#to_h
(available in Ruby 2.1+)
h.map { |k, v| [k, v.reduce(:+)]}.to_h
# => {"20141113"=>1, "20141114"=>2}
Upvotes: 3