ruby symbol

In the case given below, we have three strings with the same value.

hello1 = "Hello"
hello2 = "Hello"
hello3 = "Hello"

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 little memory as possible. That’s where symbol comes in picture.

hello1 = :hello
hello2 = :hello
hello3 = :hello

In this case, we created three symbols. However, the value is same for all the three symbols, so Ruby will treat them as a single symbol. 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 in fact the same item, then they will have the same object_id.

puts "hello".object_id 
puts "hello".object_id 
puts "hello".object_id

puts :hello.object_id
puts :hello.object_id
puts :hello.object_id

Even though the string values are the same, the object_id value is different for strings. This means all the strings are stored as different units.

On the other hand, the object_id value for each symbol is the same. It means all these symbols are the same.

Convert a String Into a Symbol A string can be converted into a symbol by using the method to_sym.

puts "bobo".to_sym

A symbol can be converted into a string by using the method to_s.

puts :bobo.to_s

Symbols are immutable. It means that once a symbol has been created it can’t be changed. We can’t append anything to a symbol.

puts :bobo << "world"
String#<< not supported. Mutable String methods are not supported in Opal.

Symbols are used a lot for method arguments. Later we will see more usage of it.

class Person
    attr_reader :name
    attr_writer :height

    def initiallize
        @name = name
        @height = height

bobo = => 'bozai', :height => '65')

Symbols are used a lot as hash keys.

one_person1 = { "name" => "Bobo", "age" => 25}
age_of_peson = one_person1["age"]

In the case provided above, we used the string age twice. It means Ruby had to create two strings with the same value. Creating more strings take more memories.

one_person2 = {:name => 'Bobo', :age => 47 }
age_of_person = one_person2[:age]

In the case given above, instead of string symbols are used as keys. It means once the symbol :age was created then the same symbol is used when the value is retrieved. For the whole operation only once :age symbol was created and it helps save memory.