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

时间:2016-11-13 12:41:42

标签: ruby

我想转换:

[:one, :two, :three]

为:

{one: :one, two: :two, three: three}

到目前为止,我正在使用它:

Hash[[:basic, :silver, :gold, :platinum].map { |e| [e, e] }]

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

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

3 个答案:

答案 0 :(得分:6)

Array#zip

a = [:one, :two, :three]
a.zip(a).to_h
#=> {:one=>:one, :two=>:two, :three=>:three}

Array#transpose

[a, a].transpose.to_h
#=> {:one=>:one, :two=>:two, :three=>:three}

答案 1 :(得分:1)

以下是map的另一种方式:

>> [:one, :two, :three].map { |x| [x,x] }.to_h
=> {:one=>:one, :two=>:two, :three=>:three}

答案 2 :(得分:1)

我承认了一个挂断:如果有选择,我更喜欢从头开始构建哈希,而不是创建一个数组并将其转换为哈希。

[:one, :two, :three].each_with_object({}) { |e,h| h[e]=e }
  #=> {:one=>:one, :two=>:two, :three=>:three}
相关问题