How to build a Ruby hash from two identical array sizes?

I have two arrays

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

and

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

I want to

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

How to do it?

+74
arrays ruby hash
Jul 29 '10 at 5:20
source share
3 answers
 h = Hash[a.zip b] # => {:baz=>1, :bof=>2, :bar=>"world", :foo=>"hello"} 

... Damn, I love Ruby.

+168
Jul 29 '10 at 5:25
source share

Just wanted to point out that there is a slightly cleaner way to do this:

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

I have to agree to the part "I love Ruby", though!

+26
Mar 25 '14 at 0:07
source share

How about this?

 [a, b].transpose.to_h 

If you are using Ruby 1.9:

 Hash[ [a, b].transpose ] 

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

+13
May 24 '14 at 11:44
source share



All Articles