Timothy Goddard
3/4/2006 11:28:00 PM
A symbol is represented internally as a number (an index in the symbol
table), but when programming in Ruby this is neither important nor
visible.
You may have seen in many C libraries how enums are used to represent
possible states. A number is used internally, but you use the constant
created in the enum as a label for a possible state or one of a few
possible options. This makes your program more easily understood and
much more easily altered.
In Ruby, a symbol is like the constant created in a C enumumeration.
You can't control the number assigned, and symbols have no logical
order, but two symbols with the same name will always be equal within
any Ruby process. You use them in many of the same places you would use
an enum. If you want your Warrior class to have the states 'able',
'injured', or 'dead', you could use the symbols :able, :injured, and
:dead. These are much faster to compare than the strings 'able',
'injured' and 'dead' as they are converted internally to a numeric
representation.
Think of a symbol as a string which is faster to compare with other
symbols but is slower to convert to a string for display or alteration
of the associated text. If you need to display something a lot or add
to the text associated with a symbol, it should probably be a string
instead. If a string is being used mostly as a label of state, it
should probably be a symbol instead.