j-zhang
j-zhang

Reputation: 703

How to count value count by different keys in a hash?

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

Answers (2)

Cary Swoveland
Cary Swoveland

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

falsetru
falsetru

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

Related Questions