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 :)
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!
Here’s how you can create a variable in Ruby:
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.
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
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.
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.
irb & do this:
orange& give it a value of
apple& give it a 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!