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:
Syntax
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
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]
Login to try C/C++/Java/PHP code in the editor
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
- Expecting
:activeand"active"to be equal, when a symbol and a string are different objects. - Writing
person["name"]for a hash created withname:, which returnsnilbecause the key is a symbol. - 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: