← Back to Ruby Course | Chapter 5: Hashes | Lesson 6 of 7

Symbol Keys

Symbol keys use names like :name as the labels in a hash, which is the usual Ruby habit. It is like using short, reusable tags as drawer labels.

In this page:

  1. Symbol Keys
Syntax
ruby
hash = { name: value1, other_name: value2 }
hash[:name]

Symbol Keys

Using symbols (:name) as hash keys is the idiomatic Ruby convention, since symbols are immutable and compare faster than strings.

The shorthand { name: "Alice" } syntax is specifically for symbol keys and is equivalent to { :name => "Alice" }. Mixing symbol and string keys in the same hash is legal but usually a sign of inconsistent design.

Note: { name: "Alice" } and { :name => "Alice" } are exactly equivalent -- the colon-shorthand is just newer, more concise syntax.

Example: Symbol Keys

markup
options = { color: "red", size: "large" }
same_thing = { :color => "red", :size => "large" }

puts options == same_thing
puts options[:color]
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Mixing "color" and :color as keys, so options["color"] returns nil.
  2. Writing { color => "red" } without a colon, which looks for a variable named color.
  3. Using keys with spaces or dashes in the short form such as { first-name: 1 }, which is a syntax error; use "first-name": 1 or :"first-name".
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.