Lesson 6 of 23 · Ruby 3.3
Use symbols as labels
Represent a named state with a symbol and compare it with other labels.
Learn
A Symbol is a value used as a named label. Write a colon before a simple name, such as :waiting. A program can use a small vocabulary of symbols to describe states without treating those states as editable message text.
Assign symbols to variables just like other values, and compare them with ==. p displays a symbol with its colon, which helps distinguish it from a string. A symbol such as :waiting is different from the string "waiting" even though their letters match.
Use a string when you need text for a message and a symbol when an API or your own program calls for a named identifier. to_s converts a symbol to a string; to_sym converts a string to a symbol. These calls return converted values.
Example
state = :waiting
p state
p state == :waiting
p state == :finishedExperiment
Predict the comparison results, then run. Change only the assigned state to :finished and check which results change.
Run to compare a symbol with text. Change the comparison to label.to_s == text, then inspect why the result changes.