How to build a Ruby hash out of two equally-sized arrays?

RubyArraysHash

Ruby Problem Overview


I have two arrays

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

and

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

I want

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

Any way to do this?

Ruby Solutions


Solution 1 - Ruby

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

...damn, I love Ruby.

Solution 2 - Ruby

Just wanted to point out that there's a slightly cleaner way of doing this:

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

Have to agree on the "I love Ruby" part though!

Solution 3 - Ruby

How about this one?

[a, b].transpose.to_h

If you use Ruby 1.9:

Hash[ [a, b].transpose ]

I feel a.zip(b) looks like a is master and b is slave, but in this style they are flat.

Solution 4 - Ruby

Just for curiosity's sake:

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%

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmačekView Question on Stackoverflow
Solution 1 - RubyjtbandesView Answer on Stackoverflow
Solution 2 - RubyLethjakmanView Answer on Stackoverflow
Solution 3 - RubyJunichi ItoView Answer on Stackoverflow
Solution 4 - Rubythe Tin ManView Answer on Stackoverflow