Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

hash

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?

like image 724
maček Avatar asked Jul 29 '10 05:07

maček


People also ask

How do you turn an array into a hash in Ruby?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

How do you compare two arrays in Ruby?

Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.

How do you create a hash in Ruby?

In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.

What is the difference between a hash and an array in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key.


2 Answers

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

...damn, I love Ruby.

like image 195
jtbandes Avatar answered Sep 28 '22 05:09

jtbandes


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!

like image 22
Lethjakman Avatar answered Sep 28 '22 05:09

Lethjakman