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

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


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

...damn, I love 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!


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.