在汇总值时散列的数组

use*_*239 0 ruby

我有一个数组如下:

[[172, 3], 
 [173, 1], 
 [174, 2], 
 [174, 3], 
 [174, 1]]
Run Code Online (Sandbox Code Playgroud)

我想转换成数组,但总结匹配键的值.所以我得到以下内容:

{172 => 3, 173 => 1, 174 => 6}
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Ste*_*fan 7

我该怎么做呢?

一次解决一个问题.

鉴于你的阵列:

a = [[172, 3], [173, 1], [174, 2], [174, 3], [174, 1]]
Run Code Online (Sandbox Code Playgroud)

我们需要一个额外的哈希:

h = {}
Run Code Online (Sandbox Code Playgroud)

然后我们必须遍历数组中的对:

a.each do |k, v|
  if h.key?(k) # If the hash already contains the key
    h[k] += v  # we add v to the existing value
  else         # otherwise
    h[k] = v   # we use v as the initial value
  end
end

h #=> {172=>3, 173=>1, 174=>6}
Run Code Online (Sandbox Code Playgroud)

现在让我们重构它.条件看起来有点麻烦,如果我们只是添加一切怎么办?

h = {}
a.each { |k, v| h[k] += v }
#=> NoMethodError: undefined method `+' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

糟糕,因为散列的值最初是不起作用的nil.我们来解决这个问题:

h = Hash.new(0) # <- hash with default values of 0
a.each { |k, v| h[k] += v }
h #=> {172=>3, 173=>1, 174=>6}
Run Code Online (Sandbox Code Playgroud)

看起来很好.我们甚至可以使用以下方法去掉临时变量each_with_object:

a.each_with_object(Hash.new(0)) { |(k, v), h| h[k] += v }
#=> {172=>3, 173=>1, 174=>6}
Run Code Online (Sandbox Code Playgroud)