kfeo8g
3.816K
· July 2012 ·
Bashir microphone square

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"
Sign in or sign up to add your response.

1 Response

2410
Fe757c8b244660deb28c3ef6330cb51e
Featured Programming Job

Senior Software Engineer
·
Washington, DC
·
Full Time
Search all programming jobs