【问题标题】:Is there a way to convert this array to a hash without the inject method? [closed]有没有办法在没有注入方法的情况下将此数组转换为哈希? [关闭]
【发布时间】:2017-05-11 04:49:22
【问题描述】:
animals = [['dogs', 4], ['cats', 3], ['dogs', 7]]

将动物转化为:

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

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: arrays ruby ruby-hash


【解决方案1】:

你可以使用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}

【讨论】:

  • 我同意,块名称会更好读
【解决方案2】:

我使用了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}

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      【解决方案4】:

      这是通过遍历每个数组元素来完成的另一种方法:

      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
      

      【讨论】:

      • 这很好。谢谢!
      • 不客气 CJ Jean :)
      【解决方案5】:

      如果您使用的是 ruby​​ 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}
      

      【讨论】:

      猜你喜欢
      • 2011-11-23
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 2017-07-15
      • 2019-08-27
      相关资源
      最近更新 更多