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

问题描述 投票:83回答:4

我有两个数组

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

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

我想要

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

任何方式吗?

ruby arrays hash
4个回答
191
投票
h = Hash[a.zip b] # => {:baz=>1, :bof=>2, :bar=>"world", :foo=>"hello"}

...该死,我爱露比。


31
投票

只是想指出,有一种更简洁的方法:

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

虽然必须同意“我爱Ruby”这一部分!


15
投票

这个怎么样?

[a, b].transpose.to_h

如果使用Ruby 1.9:

Hash[ [a, b].transpose ]

[我觉得a.zip(b)看起来像a是主控,b是从属,但在这种样式下它们是扁平的。


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%
© www.soinside.com 2019 - 2024. All rights reserved.