Symbol in Ruby (differences from string)

One of the new concepts I encountered when I learned Ruby was a symbol. Symbols are declared by placing a colon in front of the character. When I first started studying Ruby, I was confused about the difference between symbol and string, but then I found out that there are two major differences. 


1) Immutable

Symbol is an immutable object which can be used in multiple parts. Once a symbol has been assigned a value, it is impossible to change its value. 

When you try to change the value of the symbol, the following error occurs.

2.7.4 :039 > symbol = :world
 => :world
2.7.4 :040 > symbol + :s
Traceback (most recent call last):
        4: from /usr/share/rvm/rubies/ruby-2.7.4/bin/irb:23:in `<main>'
        3: from /usr/share/rvm/rubies/ruby-2.7.4/bin/irb:23:in `load'
        2: from /usr/share/rvm/rubies/ruby-2.7.4/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe
        1: from (irb):40
NoMethodError (undefined method `+' for :world:Symbol)

On the other hand, string, which is a mutable object, can be easily modified as below.

2.7.4 :044 > string = "world"
 => "world"
2.7.4 :045 > string + "s"
 => "worlds"
2.7.4 :046 >



2) Stored in memory only once

As below, no matter how you refer to symbol, it refers to the same id in memory.

2.7.4 :023 > :world.object_id
 => 2045788
2.7.4 :024 > symbol = :world
 => :world
2.7.4 :025 > symbol.object_id
 => 2045788

On the other hand, a new object of the string is created and stored in memory whenever it's delcared.

2.7.4 :029 > "world".object_id
 => 200
2.7.4 :030 > string = "world"
 => "world"
2.7.4 :031 > string.object_id
 => 220

The interesting thing is that even if string is exactly the same character, it creates a new object.

2.7.4 :032 > "world".object_id
 => 240
2.7.4 :033 > "world".object_id
 => 260
2.7.4 :034 > "world".object_id
 => 280
2.7.4 :035 > "world".object_id
 => 300


##How to use symbol?

As we saw above, symbols are immutable and are stored only once in memory. Because of these characteristics, using symbols in Ruby is more memory efficient than using strings. It is also used as a key for hash. The adventage of using symbols as a key for hash is that it's faster than a key made of strings. *Based on comparison, using a string as a key is about 1.7 times slower than using a symbol as a key.