Symbols
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: