如何通过哈希中的不同键来计数值?

时间:2021-12-02 14:37:32

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?

我该怎么做呢?

2 个解决方案

#1


3  

Get key, sum pair:

得到钥匙,和一对:

h.map { |k, v| [k, v.reduce(:+)] }
# => [["20141113", 1], ["20141114", 2]]

And convert it to hash using Hash::[]:

并使用hash::[]将其转换为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+)

或可枚举的#to_h(在Ruby 2.1+中可用)

h.map { |k, v| [k, v.reduce(:+)]}.to_h
# => {"20141113"=>1, "20141114"=>2}

#2


1  

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.

这使用了散列#merge的形式,并接受一个块。

#1


3  

Get key, sum pair:

得到钥匙,和一对:

h.map { |k, v| [k, v.reduce(:+)] }
# => [["20141113", 1], ["20141114", 2]]

And convert it to hash using Hash::[]:

并使用hash::[]将其转换为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+)

或可枚举的#to_h(在Ruby 2.1+中可用)

h.map { |k, v| [k, v.reduce(:+)]}.to_h
# => {"20141113"=>1, "20141114"=>2}

#2


1  

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.

这使用了散列#merge的形式,并接受一个块。