Symbols

Symbols are like strings, except they are code.

Symbols are a rather strange concept to be honest, and we only introduce them because symbols are used so often and widely that you’ll very likely find them used in code elsewhere. For your first steps in learning programming we would not necessarily need them.

A symbol is written like this: :something

I.e. there is a word that is preceded by a colon. This means that normally symbols do not contain spaces. Instead, if we have symbols that consist of multiple words we would concatenate them with underscores, like so: :another_funny_symbol

A symbol is created by adding a colon in front of a word.

So when to use strings, and when to use symbols?

There’s actually no perfectly clear line or simple definition.

Symbols are unique identifiers that are considered code, not data.

If you find all of this confusing, don’t worry, many people do. You’ll understand symbols better once you get to use some of them in your code. For now you can think of them as a special, limited variation of Strings (text).

Symbols are a special, limited variation of Strings.

The technical difference

Skip the following unless you’re really curious about the underlying technical difference between Strings and Symbols.

Try this in IRB:

$ irb
> "a string".object_id
=> 70358630335100
> "a string".object_id
=> 70358640625960
> "a string".object_id
=> 70358644379620

As you can see, even though the 3 Strings created are exactly the same, every new String created has a different object_id: They’re actually different objects, even though they contain the same text.

With Symbols however:

$ irb
> :a_symbol.object_id
=> 1086748
> :a_symbol.object_id
=> 1086748
> :a_symbol.object_id
=> 1086748

We now get the same object_id for each of the Symbols, meaning they’re referring to the exact same object.

The object_id is a unique id that Ruby uses internally in order to keep track of all the objects that are flying around in the universe that makes up your program. E.g. Ruby needs to know which objects are still being useful, and which ones can be cleaned up and thrown away. The object_id is a way to identify each and any object by a unique id.

By true, false, and nil (as well as all numbers) also behave this way: Whenever you use these in your code you’ll get the same object. Try it in IRB and check their object_id.

Let’s move on though.