Working with Symbols
Learn about symbols and how they’re different from strings.
We'll cover the following
What are symbols?
Symbols are like strings, but they’re code. Symbols are a rather strange concept. We only introduced them here because they’re used so often and widely that we’ll very likely find them used in code elsewhere.
A symbol is written like this: :something
. That is, a word preceded by a colon. This means that symbols typically don’t contain spaces. Instead, if we have symbols that consist of multiple words, we would concatenate them with underscores, like so: :another_funny_symbol
Remember: A Symbol object is created by adding a colon in front of a word.
When to use strings and when to use symbols
It’s not a perfectly clear choice.
Remember: Symbols are unique identifiers that are considered code, not data.
This is a confusing topic for most new learners. Symbols are more clear when applied in code. For now, think of them as a special limited variation of strings (text).
The technical difference
To appreciate the underlying technical difference between strings and symbols, try this:
puts "a string".object_idputs "a string".object_idputs "a string".object_id
Notice that even though the three strings created are exactly the same, each has a different object_id
. They’re different objects, even though they contain the same text.
With symbols, however, we see the following:
puts :a_symbol.object_idputs :a_symbol.object_idputs :a_symbol.object_id
We now get the same object_id
for each symbol, meaning that they’re referring to the exact same object.
The object_id
is a unique ID that Ruby uses internally to track all objects in a program. In other words, Ruby needs to know which objects remain useful and which ones can be discarded. The object_id
is a way to identify an object by a unique ID.
The true
, false
, and nil objects (and all numbers) also behave this way. Whenever we use these in code, we get the same object. Try checking their object_id
in the playground above.