Hitchhiker’s Guide to Ruby Variables

Learn fast how to play with data and scopes in Ruby.

Sylwia Vargas
Mar 12, 2020 · 3 min read
Image for post
Image for post
Photo by Miriam Espacio from Pexels

There are a few variable types in Ruby and that, I see, in the beginning confuses people a great deal. Welcome to my guide — I will use examples that refer to “The Hitchhiker’s Guide to the Galaxy” by Douglas Adams because it turned 42 this week. I’ll explain different variables starting from the most local in scope to the most global. Shall we begin?

1. Local variables

these are declared by writing their name, then the = sign and their value, for instance:

favorite_quote = "Don't Panic."

the scope of this variable is exactly where it is declared: if in a method, only the method will know about it. To see it for yourself, try this in your irb:

favorite_quote = "Don't Panic."def what_is_the_fav_quote
puts "My fav quote it #{favorite_quote}"
end
what_is_the_fav_quote

You should get an error undefined local variable or method `favorite_quote' for main:Object — it’s because the method has no knowledge of the variable that happened somewhere else.
There is one more thing to know about these variables: they can be overwritten. See here:

favorite_quote = "Don't Panic."
favorite_quote = 42

I didn’t change only the value but also its datatype (from a string to an integer to).

2. Instance variables

When you instantiate an instance of a class, you can set an instance variable with a @ and its name:

class Person    attr_accessor :name   

@@all = []
def initialize(name)
@name = name
@@all << self
end

def self.all
@@all
end
end

Now, let’s create a new Person and immediately check this person’s name:

Person.new("Marvin The Paranoid Android")
Person.all.first.name

How to decide if a variable should be instance or class? Well, if you think the data it holds is something specific to an individual object (e.g. every person has a name but it’s a different name; or, every citizen/resident has an SSN but we wouldn’t like others to know it), then you’d wanna make it an instance variable.

3. Class variables

Now, when I had to first conceptualize class variables, I imagined IRS that needs access to all people’s names and SSNs. That would be the @@all in the above example. In your experience with beginner’s Ruby you will most probably use class variables only in this very case: @@all.

4. Constants

Imagine that there is some data you want all functions in your class have an access to. For instance, you are making a game that’s set in “Hitchhiker’s Guide to the Galaxy” and you want to record forever what the answer to the Ultimate Question of Life, the Universe, and Everything is. You’d save it to a constant, declared in all caps:

ANSWER_TO_THE_ULTIMATE_QUESTION_OF_LIFE_THE_UNIVERSE_AND_EVERYTHING = 42

now. try overwriting it:

ANSWER_TO_THE_ULTIMATE_QUESTION_OF_LIFE_THE_UNIVERSE_AND_EVERYTHING = "puppies"

You’ll get the errors:

warning: already initialized constant ANSWER_TO_THE_ULTIMATE_QUESTION_OF_LIFE_THE_UNIVERSE_AND_EVERYTHINGwarning: previous definition of ANSWER_TO_THE_ULTIMATE_QUESTION_OF_LIFE_THE_UNIVERSE_AND_EVERYTHING was here

That’s because constant never change. It’s constant. You cannot overwrite it or change its datatype. So… that’s how it should be but how is it, really?

ANSWER_TO_THE_ULTIMATE_QUESTION_OF_LIFE_THE_UNIVERSE_AND_EVERYTHING=> "puppies"

WHAT! It changed. Well. Ruby trusts you blindly. It will give you a warning but still obey what you want it to do. This is why the constants in Ruby are somewhat fake and also not my favorite type.

5. Global variables

Now, imagine a multi-file multi-class app. How can you make data travel easily? Enter global variables, declared with a $:

$book_data = {author: "Douglas Adams", year_published: 1978}

Now, you can use the data in the variable as much as you want across the app, provided that you put require [path to the file] (e.g. require ./test.rb)

The Startup

Medium's largest active publication, followed by +771K people. Follow to join our community.

Sylwia Vargas

Written by

I teach React, Redux, JavaScript, Ruby, Rails at Flatiron School and Yale University | Follow me: https://twitter.com/sylwiavargas

The Startup

Medium's largest active publication, followed by +771K people. Follow to join our community.

Sylwia Vargas

Written by

I teach React, Redux, JavaScript, Ruby, Rails at Flatiron School and Yale University | Follow me: https://twitter.com/sylwiavargas

The Startup

Medium's largest active publication, followed by +771K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store