Symbols
| What a symbol is | |
| Symbols vs strings | |
| Symbols as hash keys | |
| To_sym and to_s |
What a symbol is
A symbol is a small fixed name with a leading colon, such as admin or ok. Symbols label things rather than hold text: roles, states, and option names are classic examples.
role = :admin
puts role # prints admin
The same symbol always means the same name wherever it appears. That makes symbols cheap to compare and ideal for marking fixed choices in your code.
Symbols vs strings
Strings hold changeable text for messages and user input, while symbols name fixed ideas inside the program. A symbol and a string with the same letters are different objects and never equal to each other.
:admin.to_s # => "admin"
"admin" == :admin # => false
Symbols as hash keys
Hashes pair keys with values, and symbols are the most popular keys because they read well and compare fast. Write each pair as name plus colon, then the value.
user = { name: "Ada", role: :admin }
puts user[:role] # prints admin
Older code writes the same pair with a rocket between key and value. Both styles build the same hash, but new code prefers the short form above:
old = { :role => :admin }
puts old[:role] # prints admin
To_sym and to_s
Two tiny converters move between the worlds. to_sym turns a string into a symbol, and to_s turns a symbol back into a string for printing or joining with other text.
"admin".to_sym # => :admin
:admin.to_s # => "admin"
puts "role=#{:admin.to_s}" # prints role=admin
Next: Truthiness: only false and nil
Article author: Arthur Isaev