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

Symbols

In this page:

  1. Symbols

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]
🔒

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.