Too Cool for Internet Explorer

Saturday, February 13, 2010

Ruby Symbols Ultimate Guide

In Ruby, a Symbol is a special class used to define a constant named label.

A symbol is defined using a colon ":" in the beginning.

Example:
:my_test_symbol

A symbol is not a string, but it has a string representation and an object identifier.

Ruby newbies ask about advantages on using constants over variables, or symbols over both, very often.

First of all, you must know there are no really Constants in Ruby. They are just a convention on variable names (starting with uppercase letters).

You can in fact, change the "constant" values along your ruby program.

That way, it is your responsibility to keep your Ruby "constants" with the same value almost all the time.



Strings, even with the same content are different objects, so, are identified differently.



So, strictly technically speaking, Symbols are pointers to memory objects containing the symbol name.

Differently from Ruby variables or even Ruby "constants", Symbol values could not be changed.



In fact you couldn’t even access the Symbol content unless through a Symbol#to_s method.



Remarkable points here are:
  • When Symbols are better then Strings?
  • Which are the advantages and drawbacks from one over the other?

If you have a few unique string values, and will use them the way they are (no concatenation, upper or lower case, no nothing), Symbols are the right tool for the job.

In any other circumstance, stick with strings. They are not that much slower then Symbols, and much more flexible.

Symbol scope is a bit different and need to be considered.



About performance, you need to have a few points in mind when dealing with a great amount of strings and Symbols:

About memory:

Strings are Garbage collected, Symbols are not.

So, Symbols will be there while your program is running, which can be a great memory consumer.

Have you ever considered how many objects you will have when you set a variable inside a loop?



When creating a great amount of Strings and Symbol, how did the operation compares in performance?



About CPU Time:

When you make Strings comparison rather then Symbols comparison, it could be a great CPU time consumer, since the comparison must be done for each character in the string.



Symbol "values" can be retrieved in many different ways:



Usage:

Symbols should be used whenever referring to a name (identifier or keyword), even if that name doesn’t exist in actual code yet.

  • Naming keyword options in a method argument list
  • Naming enumerated values.
  • Naming options in an option hash table.



That is it about Ruby Symbols