1

I have two array's as follows:

["first_name", "last_name", "email_id",  "company"]
["Andy", "Martin", "[email protected]",  nil]

I need to construct this as hash as like this.

{"first_name"=>"Andy", "last_name"=>"Martin", "email_id"=>"[email protected]", "company"=>nil}  

Is it possible in Ruby? If, then how to do that?

2
  • 2
    Yes, it's possible. Google zip method Commented Sep 19, 2013 at 13:00
  • It works well in irb, but not in my project. It gets constructed in this way.. {["first_name", "last_name", "email_id", "company"]=>["Andy", "Martin", "[email protected]", nil]} Commented Sep 19, 2013 at 13:26

2 Answers 2

5

Do this using Array#zip:

h1 = ["first_name", "last_name", "email_id",  "company"]
h2 = ["Andy", "Martin", "[email protected]",  nil]

p Hash[h1.zip(h2)]

# >> {"first_name"=>"Andy", "last_name"=>"Martin", "email_id"=>"[email protected]",    "company"=>nil}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for that. I didn't know about the zip method, I was just about to suggest using a for loop, but this way is much better
But this constructs this way: {["first_name", "last_name", "email_id", "company"]=>["Andy", "Martin", "[email protected]", nil]}
@Dinesh I didn't get you.. sorry :) The code is working... Is this not for you?
0

Even this works for me

h1 = ["first_name", "last_name", "email_id",  "company"]
h2 = ["Andy", "Martin", "[email protected]",  nil]

Hash[[h1,h2].transpose]

# >> {"first_name"=>"Andy", "last_name"=>"Martin", "email_id"=>"[email protected]",    "company"=>nil}

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.