【问题标题】:Ruby, An array of hash, convert to single hashmapRuby,一个哈希数组,转换为单个哈希图
【发布时间】:2014-12-10 05:13:54
【问题描述】:

我拥有的是:

{"Key1":[{"key2":"30"},{"key3":"40"}]}

我希望将其转换为:

{"Key1":{"key2":30,"key3":40}}

【问题讨论】:

  • 您的哈希值无效:key: value 仅适用于符号键,您必须使用 key => value

标签: ruby hash map key-value


【解决方案1】:

你可以merge多个哈希:

[{foo: 1}, {bar: 2}, {baz: 3}].inject(:merge)
#=> {:foo=>1, :bar=>2, :baz=>3}

应用于您的哈希:

hash = {"Key1"=>[{"key2"=>"30"}, {"key3"=>"40"}]}
hash["Key1"] = hash["Key1"].inject(:merge)
hash #=> {"Key1"=>{"key2"=>"30", "key3"=>"40"}}

【讨论】:

    【解决方案2】:

    我更喜欢 Stefan 的答案,因为它看起来更干净。发布这个只是为了展示另一种方法:

    hash = {"key1" => [{"key2" => "30"},{"key3" => "40"}]}
    

    那么你可以:

    hash["key1"] = Hash[hash["key1"].flat_map(&:to_a)]
    #=> {"key1"=>{"key2"=>"30", "key3"=>"40"}}
    

    但是,我做了基准测试,结果有点奇怪:

    require 'benchmark'
    
    def with_inject
      hash = {"Key1"=>[{"key2"=>"30"}, {"key3"=>"40"}]}
      hash["Key1"] = hash["Key1"].inject(:merge)
      hash
    end
    
    def map_and_flatten
      hash = {"key1" => [{"key2" => "30"},{"key3" => "40"}]}
      hash["key1"] = Hash[hash["key1"].flat_map(&:to_a)]
      hash
    end
    
    n = 500000
    Benchmark.bm(50) do |x|
      x.report("with_inject     "){ n.times { with_inject } }
      x.report("map_and_flatten "){ n.times { map_and_flatten } }
    end
    

    Ruby-1.9.2-p290 的结果 -

                            user      system      total        real
    with_inject           2.000000   0.000000   2.000000 (  2.008612)
    map_and_flatten       2.290000   0.010000   2.300000 (  2.293664)
    

    Ruby-2.0.0-p353 的结果 -

                            user      system      total        real
    with_inject            2.350000   0.020000   2.370000 (  2.366092)
    map_and_flatten        2.420000   0.000000   2.420000 (  2.419962)
    

    Ruby-2-1-2-p95 的结果 -

                            user      system      total        real
    with_inject            2.180000   0.010000   2.190000 (  2.198437)
    map_and_flatten        2.100000   0.000000   2.100000 (  2.104745)
    

    我不确定为什么在 Ruby 2.1.2 中 map_and_flattenwith_inject 快。

    【讨论】:

    • 如果哈希包含多个键值对,则您的方法不起作用,例如:Hash[[{a:1},{b:2,c:3}].map(&:flatten)]。但是你可以使用Hash[array.flat_map(&:to_a)] 来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2019-10-27
    相关资源
    最近更新 更多