Ruby Symbols
A symbol is a light name tag that starts with a colon. Programs use symbols as hash keys when the key is a fixed name.
A symbol as a name tag
The symbol :ready names one state of a program. p shows the colon, and puts prints the name without it.
status = :ready
p status
puts statusSymbol keys with the short form
In the short form, the key name comes first and a colon follows it. p shows each key with the colon in front.
person = { name: "Ana", age: 30 }
p person
puts person[:name]Symbol keys with the rocket form
The rocket form writes the colon before the name and joins the pair with =>. It builds the same hash as the short form.
person = { :name => "Ana", :age => 30 }
p person
puts person[:age]One symbol and two strings
equal? asks whether two things are the very same object. The symbol test gives true, the string test gives false, and the == test still matches the two texts.
puts :ready.equal?(:ready)
puts "ready".equal?("ready")
puts "ready" == "ready"Example
order = { item: "book", count: 2 }
order[:count] = 5
p order
puts order[:item]
puts order.lengthKey points
- A symbol starts with a colon, like :ready.
- A symbol is a name a program uses, not a piece of text it works on.
- The same symbol written twice is the same single object.
- Two strings with the same letters are two separate objects.
- The == test compares values, so two strings with the same letters pass it.
- A symbol key can be written as name: or as :name => in a hash.
In this example, the order hash uses symbol keys written in the short form. The value under count changes to 5, and p prints the whole hash. The last two lines read the item by its symbol key and count the pairs.
Note
Strings hold text that can change. Symbols hold names that stay fixed.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What does puts :ready.equal?(:ready) print?