Last Updated: May 15, 2019
·
9.409K
· bashir

Convert Ruby hash keys to symbols

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"

1 Response
Add your response