Learn Ruby
Symbol
13.1
Lesson

What is symbol

Before we discuss symbol first let’s discuss why we need symbol.

We are familiar with strings. Here are some of them.

In the above case both the variables hello and name contain strings.

In the above case we created three Strings with the same value. Even though the value is same for Ruby these are three different strings. So Ruby creates room to have all the three strings and all strings take memory.

Memory is an expensive thing when we are running programs. We want to take as less memory as possible. That’s where symbol comes in picture.

In the above case we created three symbols. However the value is same for all the three symbols so Ruby will treat it as the one symbol and this will take a lot less memory.

We can check if all the symbols refer to the same thing or not by asking each string and each symbol what is their object_id.

Ruby assigns a unique number to each item. If the two items are same then they will have same object_id.

The object_id value is different for strings even though the value is same. The object_id value for each symbol is same. It means all those symbols are same.