代码之家  ›  专栏  ›  技术社区  ›  maček

如何用两个大小相等的数组构建Ruby散列?

  •  83
  • maček  · 技术社区  · 14 年前

    a = [:foo, :bar, :baz, :bof]
    

    b = ["hello", "world", 1, 2]
    

    {:foo => "hello", :bar => "world", :baz => 1, :bof => 2}
    

    有什么办法吗?

    3 回复  |  直到 14 年前
        1
  •  208
  •   jtbandes    14 年前
    h = Hash[a.zip b] # => {:baz=>1, :bof=>2, :bar=>"world", :foo=>"hello"}
    

    …该死,我爱鲁比。

        2
  •  38
  •   Lethjakman    11 年前

    我只想指出有一个稍微干净一点的方法:

    h = a.zip(b).to_h # => {:foo=>"hello", :bar=>"world", :baz=>1, :bof=>2}
    

        3
  •  16
  •   Junichi Ito    11 年前

    这个怎么样?

    [a, b].transpose.to_h
    

    如果使用Ruby 1.9:

    Hash[ [a, b].transpose ]
    

    a.zip(b) 看起来像 a 是主人和 b

        4
  •  1
  •   the Tin Man    5 年前

    只是出于好奇:

    require 'fruity'
    
    a = [:foo, :bar, :baz, :bof]
    b = ["hello", "world", 1, 2]
    
    compare do
      jtbandes { h = Hash[a.zip b] }
      lethjakman { h = a.zip(b).to_h }
      junichi_ito1 { [a, b].transpose.to_h }
      junichi_ito2 { Hash[ [a, b].transpose ] } 
    end
    
    # >> Running each test 8192 times. Test will take about 1 second.
    # >> lethjakman is similar to junichi_ito1
    # >> junichi_ito1 is similar to jtbandes
    # >> jtbandes is similar to junichi_ito2
    
    compare do 
      junichi_ito1 { [a, b].transpose.to_h }
      junichi_ito2 { Hash[ [a, b].transpose ] } 
    end
    
    # >> Running each test 8192 times. Test will take about 1 second.
    # >> junichi_ito1 is faster than junichi_ito2 by 19.999999999999996% ± 10.0%