CodeNewbie Community 🌱

Cover image for 49 Days of Ruby: Day 8 - Symbols
Ben Greenberg
Ben Greenberg

Posted on • Originally published at on

49 Days of Ruby: Day 8 - Symbols

Welcome to day 8 of the 49 Days of Ruby! πŸŽ‰

Today is all about another important data type, the symbol!

What is a symbol?

A symbol is actually a lot closer to a string than it is to a variable. The main difference is that a string is itself a piece of data, whereas a symbol is used to identify a piece of data.

A symbol is a form of identification.

How do I use symbols?

In Ruby, a symbol can be written with a : in front of the identifier, like :jedi. The string jedi is the identifier, and the : marks it as a symbol,

Symbols can be used as the keys in a Hash:

info = { :jedi => "Luke Skywalker", :movie => "Star Wars" }

Enter fullscreen mode Exit fullscreen mode

With the above hash, you could access the Jedi by referencing the symbol identifier in info:


# => "Luke Skywalker"

Enter fullscreen mode Exit fullscreen mode

Symbols can also be used to represent an instance variable. This will come up later in more depth further in the series. For now, let's take a look at the following example:

attr_accessor :jedi

Class Heroes
  def initialize(jedi:)
    @jedi = jedi

hero = 'Luke')


# => "luke"

Enter fullscreen mode Exit fullscreen mode

What Else Do I Need To Know?

Another important thing to keep in mind about symbols is that they are immutable. What does that mean? It means that each symbol is unique and unchangeable. You cannot use the same symbol for two different things in the same object.

We will see further implementations and use cases of symbols later on in our 49 days of Ruby journey! Stay tuned!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Oldest comments (0)