Understand ruby symbols

You’ve probably already found some Ruby symbols, often used as hash keys. Example :

{:foo => 'bar'}

:foo is a symbol. ‘bar’ is a string. But we could do :

{'foo' => 'bar'}

So why use symbols ? Let’s suppose the following case :

x = :sym
y = :sym
(x.__id__ == y.__id__ ) && ( :sym.__id__ == x.__id__)

This comparison will return true. One same symbol will always be the same object in memory in your whole application. But that’s not a problem as symbols are not mutable.

And the same with strings :

x = 'string'
y = 'string'

(x.__id__ == y.__id__ ) || ( 'string'.__id__ == x.__id__)

Here, x, y and “string” are three different objects with different id. So 3 objects have been initialized in memory.

Now let’s take again our first hash with the comparison string/symbol. With the symbols version :

{:foo => 'bar'}
{:foo => 'doe'}

We create 5 objects in memory : two hashes, a symbol and two strings.
With the strings version :

{'foo' => 'bar'}
{'foo' => 'doe'}

Here, we create 6 objects in memory : two hashes and 4 strings.

In an example case like this one it won’t change anything. But in a real application context, if you replace all your symboles by strings, you’ll need to increase the memory needed to run your application. So whenever it’s appropriate, stop using strings ans use symbols :)