Chapter 8: Symbols
Symbols are simply strings that are guaranteed to be unique. Instead of quotes, symbols are indicated by adding a colon :
character behind the word. For example, :gmail
is a symbol. If you create another :gmail
it will represent the same symbol you created earlier.
A symbol looks like a variable, but it’s not. Instead, it’s much closer to a string. So what’s the difference between the string 'gmail'
and the symbol :gmail
, you ask?
When you create two strings, Ruby creates two separate objects behind the scenes. If you aren’t familiar with the concept of objects, don’t worry. It simply represents a bunch of memory addresses on your computer. Each object gets its own unique memory.
You can verify that the objects are different by printing their object_id
. Type the following code in your Ruby script and run it.
puts 'gmail'.object_id # 13900
puts 'gmail'.object_id # 16660
puts :gmail.object_id # 2385628
puts :gmail.object_id # 2385628
Notice the first two strings printed two different numbers, indicating two separate objects. However, the symbols represent the same object.
The puts command works like print, the only difference is that it adds a new line after printing the provided text. So each number is printed on a separate line. Change it to print and see for yourself.
A nice benefit of using symbols is saving memory. If you create 1000 strings, Ruby will create 1000 string objects, each occupying different blocks of memory. In contrast, 1000 symbols will represent the same block of memory.
Most of the time, you’ll use symbols in your Ruby programs as identifiers, i.e. to identify unique things. Don’t worry if that doesn’t make any sense. It will become clear as time passes.