Skip to content
AgileLogics
4 min read

Symbols

Prerequisites: Strings

A symbol is a name written with a leading colon, like :active or :email. It looks like a string, but it's used for a different job: identifying things rather than holding text.

Real-world analogy: a string is a note you might edit or print; a symbol is a name tag — a fixed label used to tell things apart.

Syntax

status = :active

How symbols differ from strings

  • The same symbol is always the same object in memory. Two strings with the same text are usually two separate objects.
  • Symbols can't be changed.
  • Comparing symbols is very fast.
p :active.object_id == :active.object_id
p "active".object_id == "active".object_id
p :active.to_s
p "active".to_sym
true
false
"active"
:active

Where you'll see them

Symbols appear most often as hash keys (covered in the Hashes lesson) and as names of options or states:

user = { name: "Ada", role: :admin }
puts "Admin!" if user[:role] == :admin
Admin!

A good rule of thumb: if you'd show it to a user or change it, use a string. If it's a fixed internal name, use a symbol.

Common mistakes

  • Comparing a string with a symbol: "admin" == :admin is false. Convert one side ("admin".to_sym) when data comes from outside.