使用两个数组Ruby构造哈希

时间:2013-09-19 12:58:48

标签: ruby arrays hash

我有两个数组如下:

["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中有可能吗?如果,那该怎么做?

2 个答案:

答案 0 :(得分: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}

答案 1 :(得分: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}