[ruby] 동일한 크기의 두 배열에서 Ruby 해시를 만드는 방법은 무엇입니까?

두 개의 배열이 있습니다

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

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

내가 원하는

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

이 작업을 수행 할 방법이 있습니까?



답변

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

… 젠장, 난 루비를 사랑해.


답변

이 작업을 수행하는 약간 더 깨끗한 방법이 있음을 지적하고 싶었습니다.

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

그래도 “I love Ruby”부분에 동의해야합니다!


답변

이건 어때?

[a, b].transpose.to_h

Ruby 1.9를 사용하는 경우 :

Hash[ [a, b].transpose ]

나는 마치 주인이고 노예 인 것처럼 a.zip(b)보이지만 이 스타일에서는 그들은 평평하다.ab


답변

호기심을 위해서 :

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%


답변