Ruby Monstas


Symbols

Symbols

Symbols are like Strings, but different.

Symbols always begin with a colon :

:coffee
:giraffe
:Tokyo

Wait, what? 😳

OK... Symbols are like stupid Strings. [citation needed]

A Symbol can't do some things that a String can:

movie = "Ghostbusters"
movie.reverse         # => "sretsubtsohG"
movie.include?("bus") # => true

vs

movie = :Ghostbusters
movie.reverse         # => NoMethodError
movie.include?("bus") # => NoMethodError

But, why do they exist? 👩‍🎓

Under the hood of Ruby, Symbols have some advantages over Strings.

Those advantages are not significant at this stage of learning the language.

If you're interested in details consider reading this:
https://ruby-for-beginners.rubymonstas.org/built_in_classes/symbols.html

Where to use Symbols

We love using Symbols as keys in Hashes

movie = { :name => "Ghostbusters" }  # very good 👍

is better than

movie = { "name" => "Ghostbusters" } # less good 👎

Using Symbols as keys in Hashes

In Hashes, Ruby allows us to put the colon : at the end of a key and omit the =>

movie = { :name => "Ghostbusters" }  # very good 👍

can be written as

movie = { name: "Ghostbusters" }     # amazing 👍👍👍

Using Symbols as keys in Hashes

Use Symbols to access the values again:

movie = { name: "The Grand Budapest Hotel" }

movie["name"]   # => nil
movie[:name]    # => "The Grand Budapest Hotel"

Summary / Recommendation

Don't use symbols as values in variables (yet!)

first_name = :Eileen  # Nay 👎
first_name = "Eileen" # Yay 👍

Do use symbols as keys in Hashes

person = { "first_name" => "Eileen" } # Nay 👎
person = { first_name: "Eileen" }     # Yay 👍

Additional Resources

Ruby For Beginners: Symbols

What questions do you have?