使用相同的键和值将数组转换为哈希的替代方法

Arn*_*Roa 2 ruby

我想转换:

[:one, :two, :three]
Run Code Online (Sandbox Code Playgroud)

至:

{one: :one, two: :two, three: three}
Run Code Online (Sandbox Code Playgroud)

到目前为止我正在使用这个:

Hash[[:basic, :silver, :gold, :platinum].map { |e| [e, e] }]
Run Code Online (Sandbox Code Playgroud)

但我想通过其他方式知道是否可能?

这是enum在模型中的Rails 定义中使用,以将值保存为db中的字符串.

And*_*eko 6

数组#zip:

a = [:one, :two, :three]
a.zip(a).to_h
#=> {:one=>:one, :two=>:two, :three=>:three}
Run Code Online (Sandbox Code Playgroud)

数组#transpose:

[a, a].transpose.to_h
#=> {:one=>:one, :two=>:two, :three=>:three}
Run Code Online (Sandbox Code Playgroud)


Car*_*and 3

我更喜欢从头开始构建哈希,而不是构建临时数组(消耗内存)并将其转换为哈希。

[:one, :two, :three].each_with_object({}) { |e,h| h[e]=e }
  #=> {:one=>:one, :two=>:two, :three=>:three}
Run Code Online (Sandbox Code Playgroud)