将数组转换为哈希并初始化为值

res*_*way 3 ruby

转换数组的最佳方法是什么?

arr = ["one", "two", "three", "four", "five"]
Run Code Online (Sandbox Code Playgroud)

哈希

{"one"=>0, "two"=>0, "three"=>0, "four"=>0, "five"=>0}
Run Code Online (Sandbox Code Playgroud)

我打算稍后用我自己的值填充'0',我现在只需要这个技术.

谢谢.

Kim*_*all 5

我不知道这是不是最好的方法:

Hash[arr.map{ |el| [el, 0] }]
Run Code Online (Sandbox Code Playgroud)


Car*_*and 5

arr.product([0]).to_h
Run Code Online (Sandbox Code Playgroud)

或版本<2.0

Hash[arr.product([0])]
Run Code Online (Sandbox Code Playgroud)