Skip to main content

How to Tell Symbol Keys from String Keys in a Ruby Hash

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

In Ruby, :name and 'name' are different values, so a hash stores them as different keys. Data that arrives from JSON usually has string keys, and asking it for hash[:name] returns nil instead of the value you can see.

Syntax​

Syntax
{ 'name' => 'Ada' }['name'] # string key
{ name: 'Ada' }[:name] # symbol key
PartWhat it does
'name' => ...Creates a string key.
name: ...Creates a symbol key, :name.
hash[key]Finds the entry only with a key of the same kind.

The Ruby literals documentation: "A Symbol represents a name inside the ruby interpreter." A symbol and a string with the same letters are still different objects, and a hash compares keys exactly.

The Example​

The example stores a name under the string key 'name', then reads it once with the string and once with the symbol.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Code​

Create a file named main.rb:

main.rb, which creates user with the string key name set to Ada, and prints user['name'] and user[] with p.

main.rb
user = { 'name' => 'Ada' }

p user['name']
p user[:name]

Step 2: Run It​

Terminal
ruby main.rb
Output
"Ada"
nil

A zsh terminal where ruby main.rb prints "Ada" and nil.

The string key found the value; the symbol found nothing. The command is the same in zsh, bash and PowerShell.

Getting Symbol Keys from JSON​

JSON.parse returns string keys: JSON.parse('{"name": "Ada"}') gave {"name" => "Ada"}. Pass symbolize_names: true to get symbols instead, which gave {name: "Ada"}. For a hash you already have, user.transform_keys(&:to_sym) returns a copy with symbol keys.

Common Mistakes​

MistakeWhat happensDo this instead
Reading a parsed JSON hash with symbolsEvery lookup returns nilUse string keys, or parse with symbolize_names: true
Mixing both kinds in one hashThe same name can exist twice, once as each kindPick one kind of key per hash
Reading the printout too quickly{"name" => "Ada"} and {name: "Ada"} look alikeLook for the quotes: quoted keys are strings

Troubleshooting​

SymptomLikely causeFix
nil for a key you can see in p hashThe printout shows "name" =>, a string keyUse hash['name']
nil from data a library returnedThe library returns string keysCheck its documentation, then match the kind

FAQ​

Which kind should I use?​

Symbols for keys you write in your own code, strings for data from outside, such as JSON or HTTP parameters.

Is there a hash that accepts both?​

Not in plain Ruby. Rails adds one, HashWithIndifferentAccess; in plain Ruby, convert the keys once.

Conclusion​

:name and 'name' are different hash keys, so look values up with the same kind the hash was built with. JSON gives string keys unless you pass symbolize_names: true.

Additional Resources​