1

我有两个数组如下:

["first_name", "last_name", "email_id",  "company"]
["Andy", "Martin", "hello@ex.com",  nil]

我需要像这样将其构造为哈希。

{"first_name"=>"Andy", "last_name"=>"Martin", "email_id"=>"hello@ex.com", "company"=>nil}  

在Ruby中可以吗?如果,那该怎么做?

4

2 回答 2

5

使用Array#zip

h1 = ["first_name", "last_name", "email_id",  "company"]
h2 = ["Andy", "Martin", "hello@ex.com",  nil]

p Hash[h1.zip(h2)]

# >> {"first_name"=>"Andy", "last_name"=>"Martin", "email_id"=>"hello@ex.com",    "company"=>nil}
于 2013-09-19T13:00:15.137 回答
0

即使这对我有用

h1 = ["first_name", "last_name", "email_id",  "company"]
h2 = ["Andy", "Martin", "hello@ex.com",  nil]

Hash[[h1,h2].transpose]

# >> {"first_name"=>"Andy", "last_name"=>"Martin", "email_id"=>"hello@ex.com",    "company"=>nil}
于 2013-09-19T14:03:07.263 回答