Skip to main content

How to Create a Hash with Symbol Keys in Ruby

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A hash stores values under keys, like a dictionary. With symbols as keys, Ruby offers a short syntax that reads almost like plain text: { title: 'Dune', year: 1965 }.

Syntax​

Syntax
<hash> = { <key>: <value>, <key>: <value> }
<hash>[:<new_key>] = <value>
<hash>[:<key>]
PartWhat it does
<key>: <value>One entry whose key is the symbol :<key>.
<hash>[:<key>]Reads a value; nil when the key isn't there.
<hash>[:<key>] = <value>Adds or replaces an entry.

The Ruby documentation for Hash: "A Hash object maps each of its unique keys to a specific value." It describes the original "hash rocket" syntax, =>, and the shorter key: value form that works "only for a key that's a symbol".

The Example​

The example describes a book with three entries, adds the number of pages, reads the title and prints the whole hash.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Hash​

Create a file named main.rb:

main.rb, which creates book with the title Dune, the author Frank Herbert and the year 1965 using symbol keys, sets book[] to 412, puts book[] and prints the hash with p.

main.rb
book = { title: 'Dune', author: 'Frank Herbert', year: 1965 }
book[:pages] = 412

puts book[:title]
p book

p prints the hash in its inspect form, which shows the keys and quoted strings.

Step 2: Run It​

Terminal
ruby main.rb
Output
Dune
{title: "Dune", author: "Frank Herbert", year: 1965, pages: 412}

A zsh terminal where ruby main.rb prints Dune and the hash with title, author, year and pages.

The new pages entry appears last: hashes keep the order you add keys in. The command is the same in zsh, bash and PowerShell.

Missing Keys​

book[:isbn] returns nil without complaint. When a missing key is a mistake, use fetch, which raised key not found: :isbn (KeyError), or give it a default: book.fetch(:isbn, 'none').

Common Mistakes​

MistakeWhat happensDo this instead
Reading book['title'] from a symbol-keyed hashnil: 'title' and :title are different keysUse book[:title]
Relying on [] for required keysA typo silently gives nilUse fetch
Writing { 'title': 'Dune' } and expecting a string keyThe quotes still create the symbol :titleUse 'title' => 'Dune' for a string key

Troubleshooting​

SymptomLikely causeFix
A value is nilThe key is misspelled, or it's a string key instead of a symbolPrint the hash with p and compare the keys
key not found (KeyError)fetch met a missing keyAdd the key, or pass a default to fetch

FAQ​

Why does the printed hash look different from older Ruby?​

Ruby 3.4 changed Hash#inspect to print symbol keys as title: "Dune"; older versions printed :title=>"Dune".

Can keys be other things than symbols?​

Yes, almost any object: strings, numbers or arrays, written with =>.

Conclusion​

{ key: value } creates a hash with symbol keys, hash[:key] reads a value and hash[:key] = value adds one. Use fetch when a missing key should be an error.

Additional Resources​

  • Hash, in the Ruby documentation.