Where developers come to connect, share, build and be inspired.

6

Convert Ruby hash keys to symbols

1948 views

Problem

you have a hash with string keys but want to access them with symbols instead.

You have:

myhash = {"name" => "James", "email" => "james@hotmail.com"}

if you try to access the hash above with symbols, you'll get nil

myhash[:name] #nil

however

myhash['name'] # "James"

Solution

There are two methods that can help you. One is symbolize_keys! which only symbolizes first level keys and withindifferentaccess which symbolizes recursively.

indifferent_hash = myhash.with_indifferent_access
indifferent_hash[:name] # "James"
indifferent_hash['name'] #"James"

or

myhash.symbolize_keys![:name] # "James"

Comments

Add a comment