Techioz Blog

同じキーと値を使用して配列をハッシュに変換する代替方法

概要

変換したい:

[:one, :two, :three]

に:

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

これまでのところ、私はこれを使用しています:

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

しかし、他の方法でそれが可能かどうか知りたいのですが?

これは、モデルの Rails enum 定義で使用し、値を文字列として db に保存します。

解決策

配列#zip:

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

配列#転置:

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