How to Tell Symbol Keys from String Keys in a Ruby Hash
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
{ 'name' => 'Ada' }['name'] # string key
{ name: 'Ada' }[:name] # symbol key
| Part | What 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.](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/programming/ruby/2026/rb-symbol-vs-string-keys-code.webp)
user = { 'name' => 'Ada' }
p user['name']
p user[:name]
Step 2: Run It
ruby main.rb
"Ada"
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
| Mistake | What happens | Do this instead |
|---|---|---|
| Reading a parsed JSON hash with symbols | Every lookup returns nil | Use string keys, or parse with symbolize_names: true |
| Mixing both kinds in one hash | The same name can exist twice, once as each kind | Pick one kind of key per hash |
| Reading the printout too quickly | {"name" => "Ada"} and {name: "Ada"} look alike | Look for the quotes: quoted keys are strings |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
nil for a key you can see in p hash | The printout shows "name" =>, a string key | Use hash['name'] |
nil from data a library returned | The library returns string keys | Check 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
- Symbol literals, in the Ruby documentation.
- Hash, in the Ruby documentation.
