Symbols
Ruby's lightweight labels
You already met symbols briefly in the hashes lesson, when you wrote keys like name: and age:. Now it is time to understand what symbols actually are and why Ruby programmers use them so often.
What a symbol looks like
A symbol is written with a leading colon, followed by a name, and no quotes.
status = :active
puts statusThis looks a little like a variable name with a colon glued to the front, but it behaves quite differently from a string.
Symbols versus strings
A string like "active" is meant to hold text that might change or be displayed to a person, such as a message someone typed in. A symbol like :active is meant to act as a fixed, internal label, more like a name tag than a piece of text. Ruby stores every use of a given symbol as the exact same single object in memory, which makes symbols slightly faster and lighter than strings.
Symbols in hashes
The most common use of symbols is as hash keys.
person = { name: "Ava", role: :student }
puts person[:name]
puts person[:role]This prints "Ava" and then "student". Notice that role itself is stored as a symbol key, and its value, :student, is also a symbol.
A simple rule of thumb
- Use a string when the text is meant to be displayed, changed, or typed by a user.
- Use a symbol when the value is a fixed, internal label, like a hash key or a status such as :active or :pending.
If you are ever unsure whether to use a string or a symbol, look at how experienced Ruby code is written. Hash keys almost always use symbols by convention.
Quick check
Q1 How is a symbol written in Ruby?
Q2 What are symbols most commonly used for in Ruby?
Want to save your progress? It's free.
Create a free account