gpt4 book ai didi

ruby - 使用相同的键和值将数组转换为散列的替代方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:39 25 4
gpt4 key购买 nike

我要转换:

[:one, :two, :three]

到:

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

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

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

但我想知道是否可以通过其他方式实现?

这是在模型中的 Rails enum 定义中使用,将值作为字符串保存在数据库中。

最佳答案

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}

关于ruby - 使用相同的键和值将数组转换为散列的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40573947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com