How to Use Ruby Variables

In this lesson you'll learn about Ruby variables!

Exactly what's a variable, why they're useful & how to use them in your Ruby programs.

Let's do this :)

What’s A Variable?

You can save a value & give it a name by using a variable.

A variable is just a label

…a name for something that you can use to reference this value in your Ruby programs.

Just like the name we give to real-world things.

When I say “apple” you know what I’m talking about.

I don’t have to describe it to you.

That’s what variables do!

Creating Local Variables

Here’s how you can create a variable in Ruby:

age = 32

Now when you type age Ruby will translate that into 32.

Try it!

There is nothing special about the word age.

You could use bacon = 32 & the value would still be 32.

Variables are just names for things.

Using Variables

To use a variable you write its name:

age * 10
# 320

You can combine multiple variables together:

age = 32
multiplier = 10

age * multiplier

And save the result of calculations into a new variable:

total = age * multiplier


If you’re running this code from a file, instead of irb, then you should use a method like puts to see the value of the variable.


puts total
# 320

Ruby Variable Types

In Ruby we have different variable types.

What you have seen here are called “local variable”.

But there are other kinds too:

You don’t need to worry too much about these right now, but it’s good to know they exist.

The difference between them?

It’s on their “scope”.

A variable scope answers this question:

“From where can I access this variable?”

This is only going to matter when you start learning about Object-Oriented Programming, we’ll revisit this topic by then.

Practice Time!


This concept of variables is very useful, if you don’t use variables you would have to repeat every single calculation every time that you want to refer to it.

And you wouldn’t have a way to name things so you know what they are.

Open up irb & do this:

  1. Create a variable named orange & give it a value of 300.
  2. Create another variable named apple & give it a value of 120.
  3. Multiply the value of orange & apple, then assign the result to a new variable total.

When you feel comfortable using variables then go to the next lesson.

And if you haven’t installed Ruby yet make sure to check the first lesson of this Ruby tutorial for beginners.

Keep going! You’re doing great!