Arnold Roa Arnold Roa - 1 year ago 100
Ruby Question

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

I want to convert:

[:one, :two, :three]


{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
definition in model, to save values as strings in db.

Answer Source

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}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download