How to understand symbols in Ruby

Consider this:

x = :sym
y = :sym
(x.__id__ == y.__id__ ) && ( :sym.__id__ == x.__id__) # => true

x = "string"
y = "string"
(x.__id__ == y.__id__ ) || ( "string".__id__ == x.__id__) # => false

So, however you create a symbol object, as long as its contents are the same, it will refer to the same object in memory. This is not a problem because a symbol is an immutable object. Strings are mutable.


(In response to the comment below)

In the original article, the value is not being stored in a symbol, it is being stored in a hash. Consider this:

hash1 = { "string" => "value"}
hash2 = { "string" => "value"}

This creates six objects in the memory — four string objects and two hash objects.

hash1 = { :symbol => "value"}
hash2 = { :symbol => "value"}

This only creates five objects in memory — one symbol, two strings and two hash objects.

Leave a Comment