6.1. Symbols

A symbol in Ruby is an instance of the class Symbol. The syntax is simple in the typical case: a colon followed by an identifier.

A symbol is like a string in that it corresponds to a sequence of characters. It is unlike a string in that each symbol has only one instance (just as a Fixnum works). Therefore, there is a memory or performance issue to be aware of. For example, in the following code, the string "foo" is stored as three separate objects in memory, but the symbol :foo is stored as a single object (referenced more than once):

array = ["foo", "foo", "foo", :foo, :foo, :foo]

Some people are confused by the leading colon on a symbol name. There is no need for confusion; it’s a simple matter of syntax. Strings, arrays, and ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.