When I started to work with Ruby I was puzzled by the symbol – text preceded by a colon character, as in
What exactly is a symbol, I wondered? And why is it used? I set out to find an explanation.
Enlightenment came with Kevin Clark’s article Understanding Ruby Symbols. The key for me was Thomas Aylott’s comment:
Symbols are like constants whose name is their value. Just like the number 5 has both the name 5 and the value 5 so the symbol :howdy is the word howdy
That explained what a symbol represents. So why are symbols useful? In Ruby strings are mutable, so every time you create another string with the value “document_title” it is a new object which takes up space in memory (unlike Java’s handling of string literals, for example). In his article Kevin Clark gives an example of how this could become an issue when using strings as hash keys. A symbol provides a solution to the problem because, as explained in the free on-line version of the first edition of Programming Ruby,
The same Symbol object will be created for a given name string for the duration of a program’s execution, regardless of the context or meaning of that name.
Another benefit is that because symbols can be compared by object id, comparison of symbols is faster than comparison of the strings they represent.
So when is it useful to use a symbol?
- Use symbols instead of strings as hash keys.
- If you’re going to be using the same string value in many places, consider using a symbol.
- Symbols are immutable and you can’t invoke string methods on them, so consider using a string if you want to be able to manipulate it.