我有两个数组如下:
["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中有可能吗?如果,那该怎么做?
答案 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}