Differences between symbols and strings in Ruby

You can think of a symbol as an immutable string. Since it can't change each time you ask for a symbol using :name syntax the ruby interpreter will return the same instance of the symbol.

First al all let's prove that.

As you can see each time we write: "Yay", we are getting a different
object. Although they contain the same characters and they are equal
they are different objects

But in the case of symbols

Also, strings can be changed

But symbols can't

This causes symbols to be often used as keys to hashes or to
be used as a substitute for enumerated types.

Bonus points:

You can freeze a string and cause it to be immutable with freeze method

You can also define 'constants'. Ruby compiler will consider any variable that is declared uppercased as a constant. It will raise a warning in case you change it. Anyway it will allow you to do so:

Leave a Reply

Your email address will not be published. Required fields are marked *