2

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.

4
  • 4
    What do you want as a result? Commented Nov 24, 2015 at 17:13
  • 4
    The arrays are different lengths so it isn't clear what the resultant Hash should look like. Commented Nov 24, 2015 at 17:18
  • 4
    example of your expected result? Commented Nov 24, 2015 at 17:26
  • Best not to post a question and walk away, as it my not be as clear as you think it is, especially considering that you are new to Ruby. Please edit to add the desired result (as opposed to doing that in a comment). Commented Nov 24, 2015 at 20:31

3 Answers 3

6
x = [:foo, :bar, :baz]
y = [1, 2, 3]
x.zip(y).to_h # => {:foo=>1, :bar=>2, :baz=>3}
Sign up to request clarification or add additional context in comments.

2 Comments

This implies that { "NY"=>"apple", "SF"=>" banana", "NL"=nil, "SY"= nil } is the desired result. I may be wrong, but I think you have answered a different question.
@CarySwoveland, who knows :)
2

You can use the zip method, like so:

Hash[array_2.zip(array_1)]

1 Comment

This returns { 'apple'=>'NY', 'banana'=>'SF' }. How does that satisfy the requirement that "each object in array_1 will be assigned with the objects in array_2"?
2
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"]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.