Symbols

Learn what symbols are and how to use them in Ruby.

We'll cover the following...

Define symbols

Symbols are similar to strings. Symbols are instances of the Symbol class, just as strings are instances of the String class). Here is how we can define a symbol in Ruby:

# assign symbol :something to variable "x"
x = :something

Compare the code above to the string’s definition:

x = "something"
x = 'something' # alternative syntax

Uses of symbols

We use symbols when, logically, a variable belongs to a set of similar values, for example:

order.status = :confirmed
order.status = :cancelled

The :confirmed symbol can be used in other parts of a program. But why are we using symbols in Ruby when the code above works well with strings? Consider: ...