How to understand symbols in Ruby How to understand symbols in Ruby ruby ruby

How to understand symbols in Ruby


Consider this:

x = :symy = :sym(x.__id__ == y.__id__ ) && ( :sym.__id__ == x.__id__) # => truex = "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.


I was able to grock symbols when I thought of it like this. A Ruby string is an object that has a bunch of methods and properties. People like to use strings for keys, and when the string is used for a key then all those extra methods aren't used. So they made symbols, which are string objects with all the functionality removed, except that which is needed for it to be a good key.

Just think of symbols as constant strings.


The symbol :ruby does not contain "red" or "programming". The symbol :ruby is just the symbol :ruby. It is your hashes, patient1 and patient2 that each contain those values, in each case pointed to by the same key.

Think about it this way: If you go into the living room on christmas morning, and see two boxes with a tag on them that say "Kezzer" on them. On has socks in it, and the other has coal. You're not going to get confused and ask how "Kezzer" can contain both socks and coal, even though it is the same name. Because the name isn't containing the (crappy) presents. It's just pointing at them. Similarly, :ruby doesn't contain the values in your hash, it just points at them.