如何从两个大小相同的数组中构建Ruby哈希?

时间:2010-07-29 05:20:09

标签: ruby arrays hash

我有两个数组

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

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

我想要

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

有什么办法吗?

4 个答案:

答案 0 :(得分:189)

h = Hash[a.zip b] # => {:baz=>1, :bof=>2, :bar=>"world", :foo=>"hello"}

...该死的,我喜欢Ruby。

答案 1 :(得分:31)

只是想指出这样做的方法稍微清晰一点:

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

必须同意"我喜欢Ruby"部分虽然!

答案 2 :(得分:14)

这个怎么样?

[a, b].transpose.to_h

如果你使用Ruby 1.9:

Hash[ [a, b].transpose ]

我觉得a.zip(b)看起来a是主人,b是奴隶,但是这种风格是平的。

答案 3 :(得分:0)

只是出于好奇:

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%