Understanding Ruby symbols
December 4, 2007
Symbols are one of the most misunderstood Ruby features. Let’s try to explain it as lay as possible.
The way I finally catched it is thinking about symbols as constants, whose value is the same as their name. The same as the integer 5 has the name 5 and the value 5, the symbol :thing has the name thing and the value “thing”. That’s why we can open an irb and do this:
irb(main):008:0> puts :myname myname => nil irb(main):009:0> :myname => :myname
Remember, symbols are not strings, therefore this is not possible:
irb(main):010:0> puts :myname + :othername
NoMethodError: undefined method `+' for :myname:Symbol
from (irb):10
Instead we can get the value of the symbol, and convert it to a String to get this:
irb(main):011:0> puts :myname.to_s + :othername.to_s mynameothername => nil
Very cute. So what’s the point?Symbols are mainly used to save memory. They have only one occurrence within a Ruby program, while strings with the same name are stored in different positions of memory every time. Check this:
irb(main):012:0> "string".object_id => 24125620 irb(main):013:0> "string".object_id => 24122170 irb(main):014:0> :string.object_id => 68258 irb(main):015:0* :string.object_id => 68258
And don’t forget that symbols are objects, just like everything in Ruby. They have a name and a string value, as we said, but an integer value to be recognized by the program as well, a value that is always constant. That brings many performance benefits (while comparing symbols, for example). They are like strings with a value that must not be changed.
Advertisement
If you’ve done any perl, you’d know them as being like ‘barewords’, where an unrecognised string is treated as a string with the value of itself.
Liked the simplified approach of your explanation. Too good.
I think, symbol is similar to immediate value.
Could you tell me the scenarios where symbols should be used over string and vice versa?
hi raj,
rails programming provides many situations in which you want to fix the name of your String, which is the case where you want to use symbols. E.g.
url_for(:action => :index) over url_for(:action => ‘index’)
params[:country_id] over params['country_id']