标签: ruby
我有一个数组[1,2,3]并希望从中创建哈希,因此结果为{"kangaroo"=>1, "moose"=>2, "mouse"=>3}。最好的方法是什么?
[1,2,3]
{"kangaroo"=>1, "moose"=>2, "mouse"=>3}
答案 0 :(得分:10)
怎么样:
Hash[%w(kangaroo moose mouse).zip [1,2,3]] # => {"kangaroo"=>1, "moose"=>2, "mouse"=>3}
Array#zip结合了两个数组元素:
Array#zip
%w(kangaroo moose mouse).zip [1,2,3] # => [["kangaroo", 1], ["moose", 2], ["mouse", 3]]
Hash::[]从此数组创建一个Hash。
Hash::[]