How to Use Variables in Ruby
In this lesson you'll learn about variables, one of the most fundamental tools for any programming language.
We'll cover...
- 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”.
Example:
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.
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
Important:
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.
Example:
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 (
$apple
) - instance variable (
@apple
) - class variable (
@@apple
) - constant (
APPLE
)
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 Time!
Practice working with variables so you can develop an understanding of how they work.
Now:
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.
Open up irb
& do this:
- Create a variable named
orange
& give it a value of300
. - Create another variable named
apple
& give it a value of120
. - Multiply the value of
orange
&apple
, then assign the result to a new variabletotal
.
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!
Copyright RubyGuides.com