我有两个数组如下:
["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中可以吗?如果,那该怎么做?
使用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}
即使这对我有用
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}