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[{|k, v| [k.to_sym, v]}]
=> {:one=>"uno", :two=>"dos", :three=>"tres"}

The Hash#map method surprisingly returns an Array:

>>{|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!


Leave a Reply

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

You are commenting using your 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