2017-05-11 52 views

回答

1

這是通過每個數組元素迭代完成的另一種方法:

animals = [['dogs', 4], ['cats', 3], ['dogs', 7]] 

result = Hash.new(0) 

animals.each do |animal| 
    result[animal[0]] += animal[1].to_i 
end 

p result 
+0

這很好。謝謝! –

+0

歡迎CJ讓:) –

4

您可以使用each_with_object

=> array = [['dogs', 4], ['cats', 3], ['dogs', 7]] 
=> array.each_with_object(Hash.new(0)) do |(pet, n), accum| 
=> accum[pet] += n 
=> end 
#> {'dogs' => 11, 'cats' => 3} 
+0

我同意,塊名稱會更好讀 –

-1

你如果您使用r,可以使用to_h方法uby < = 2.1。

例如:

animals = [['dogs', 4], ['cats', 3], ['dogs', 7]] 
animals.group_by(&:first).map { |k,v| [k,v.transpose.last.reduce(:+)]}.to_h # return {"dogs"=>11, "cats"=>3} 
+0

http://stackoverflow.com/questions/43906745/is-there-a-way-to-convert-this-array-to-a -hash-without-the-inject-method#comment74846947_43906834 –

+0

我修復了答案。 – mijailr

+0

'reduce'是'inject'的別名! –

3

我用Enumerable#group_by。更好的方法是使用計數散列,@Зелёный完成了。

animals = [['dogs', 4], ['cats', 3], ['dogs', 7]] 

animals.group_by(&:first).tap { |h| h.keys.each { |k| h[k] = h[k].transpose[1].sum } } 
    #=> {"dogs"=>11, "cats"=>3} 
2
data = [['dogs', 4], ['cats', 3], ['dogs', 7]] 
data.dup 
    .group_by(&:shift) 
    .map { |k, v| [k, v.flatten.reduce(:+)] } 
    .to_h 

隨着Hash#merge

data.reduce({}) do |acc, e| 
    acc.merge([e].to_h) { |_, v1, v2| v1 + v2 } 
end 

data.each_with_object({}) do |e, acc| 
    acc.merge!([e].to_h) { |_, v1, v2| v1 + v2 } 
end 
相關問題