Ruby – Convert every key of a hash to a symbol

There are a couple of interesting ways to convert every key of a ruby hash to a symbol. Suppose we have a hash = {“one”=>”uno”, “two”=>”dos”, “three”=>”tres”} and would like to convert it to {:one=>”uno”, :two=>”dos”, :three=>”tres”}.

One approach is to convert the hash to an array of arrays and then reconstruct the hash:

>> Hash[hash.map{|k, v| [k.to_sym, v]}]
=> {:one=>"uno", :two=>"dos", :three=>"tres"}

The Hash#map method surprisingly returns an Array:

>> hash.map{|k, v| [k.to_sym, v]}
=> [[:one, "uno"], [:two, "dos"], [:three, "tres"]]

Alternatively, the inject method can be used to create a new hash from the original hash:

>> hash.inject({}) { |memo, (k, v)| memo[k.to_sym] = v; memo  }

In a Rails environment, the symbolize_keys method can be used, but that is no fun!

hash.symbolize_keys()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s