DEV Community

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

Posted on

5 2

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:

info[:jedi]

# => "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
  end
end

hero = Hero.new(jedi: 'Luke')

hero.jedi

# => "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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay