有没有办法在没有inject方法的情况下将此数组转换为哈希?

时间:2017-05-11 04:49:23

标签: arrays ruby ruby-hash

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

将动物转换为:

{'dogs' => 11, 'cats' => 3}

4 个答案:

答案 0 :(得分: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}

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:-1)

如果您使用ruby< = 2.1。

,则可以使用to_h方法

例如:

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}