← Back to Ruby Course | Chapter 2: Variables & Types | Lesson 6 of 7

Symbols

A symbol is a lightweight name that starts with a colon, like a label that always means the same thing. It is used for names and keys because it is quick and never changes.

In this page:

  1. Symbols
Syntax
ruby
symbol = :name
hash = { name: value }

Symbols

A symbol, written as :name, is an immutable, interned identifier -- unlike a string, two symbols with the same name always refer to the exact same object in memory, making them faster to compare.

Symbols are commonly used as hash keys and method names since they're lightweight and unique. They're one of Ruby's more distinctive features compared to most other languages.

Note: Symbols are faster to compare than strings (they compare by identity, not character-by-character) which is why they're the idiomatic choice for hash keys.

Example: Symbols

markup
status = :active

puts status.class
puts :active.object_id == :active.object_id
puts "active".object_id == "active".object_id

person = { name: "Alice", role: :admin }
puts person[:name]
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. Expecting :active and "active" to be equal, when a symbol and a string are different objects.
  2. Writing person["name"] for a hash created with name:, which returns nil because the key is a symbol.
  3. Creating symbols from user input in old Ruby versions, which could not be garbage collected.
🔒

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.