Arnold Roa Arnold Roa - 2 days ago 6
Ruby Question

Alternatives to convert a array to a hash using same keys and values

I want to convert:

[:one, :two, :three]


to:

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


So far I'm using this:

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


But I would like to know if it's possible by some other way?

This is to use in a Rails
enum
definition in model, to save values as strings in db.

Answer

I admit to a hangup: given the choice, I prefer constructing hashes from scratch rather than creating an array and converting it to a hash.

[:one, :two, :three].each_with_object({}) { |e,h| h[e]=e }
  #=> {:one=>:one, :two=>:two, :three=>:three}
Comments