How to Use Variables in Ruby
In this lesson you'll learn about variables, one of the most fundamental tools for any programming language.
- Exactly what's a variable!
- Why are variables useful in Ruby
- How to use variables in your Ruby programs!
Let's do this :)
What’s A Ruby Variable?
A variable is just a label.
It’s a way to give names to things in your Ruby programs.
Like the names 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!
And they’re way more useful that you may think.
Creating Local Variables
You create variables by associating a Ruby object with a variable name.
We call this “variable assignment”.
age = 32
Now when you type
age Ruby will translate that into
There is nothing special about the word
You could use
bacon = 32 & the value would still be
Variables are just names for things.
How to Use 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
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:
- global variable (
- instance variable (
- class variable (
- constant (
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’s 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 working with variables so you can develop an understanding of how they work.
You have learned that variables are 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.
irb & do this:
- Create a variable named
orange& give it a value of
- Create another variable named
apple& give it a value of
- Multiply the value of
apple, then assign the result to a new variable
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!