Elad Kuzy
Elad Kuzy

Reputation: 51

Ruby, how to create a hash from two arrays?

I'm fairly a beginner in Ruby and I'm trying to do the following: Let's say I have two arrays:

array_1 = ["NY", "SF", "NL", "SY"]
array_2 = ["apple", "banana"]

I want to merge the arrays to a hash so each object in array_1 will be assigned with the objects in array_2

Thanks in advance.

Upvotes: 2

Views: 1467

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

h = array_1.product([array_2]).to_h
  #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

We were given Array#to_h in MRI v2.0. For earlier versions, use Kernel#Hash:

h = Hash[array_1.product([array_2])]

but beware:

array_2[0] = "cat"
array_2
  #=> ["cat", "banana"] 
h #=> {"NY"=>["cat", "banana"], "SF"=>["cat", "banana"],
  #    "NL"=>["cat", "banana"], "SY"=>["cat", "banana"]}

You may instead want:

h = array_1.each_with_object({}) { |str,h| h[str] = array_2.dup }
  #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

array_2[0] = "cat"
h #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

Upvotes: 2

ndnenkov
ndnenkov

Reputation: 36101

x = [:foo, :bar, :baz]
y = [1, 2, 3]
x.zip(y).to_h # => {:foo=>1, :bar=>2, :baz=>3}

Upvotes: 6

SHS
SHS

Reputation: 7744

You can use the zip method, like so:

Hash[array_2.zip(array_1)]

Upvotes: 2

Related Questions