ruby-on-railsrubyruby-hash

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.


Solution

  • I prefer constructing hashes from scratch rather than constructing a temporary array (which consumes memory) and converting it to a hash.

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