Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Did you know Ruby can also be used as a calculator? In this video, we're going to learn about numbers in Ruby as well as how to use irb as a simple calculator.
Code Samples
Assign a variable as a number (in irb):
a = 1
b = 2
Add two numbers together:
a + b
Subtract two numbers:
b  a
Practice
Try adding and subtracting different numbers using irb or writing your own Ruby program.

0:00
[MUSIC]

0:04
So far, we've been working pretty much exclusively with strings.

0:09
In Ruby, strings aren't the only things that we can work with.

0:14
We can also work with numbers.

0:17
And just like with strings, it's very, very easy to create a number.

0:21
The big difference is that we don't use quotes when creating numbers like we do

0:26
with strings.

0:27
We'll just leave the quotes off.

0:30
We could actually use IRB to create a very simple calculator.

0:35
Let's go ahead and check that out to see how it works.

0:38
Let's go ahead and launch IRB now so that we can work with numbers.

0:46
The easiest way to work with a number inside of IRB is to just type it,

0:52
and we can see that Ruby creates a number for us.

0:57
If we wanted to add two numbers together, we could do that as well.

1:03
And Ruby will give us the output.

1:06
Now, just like with strings, we can assign numbers to variables as well.

1:13
So I'm just going to say a is 1.

1:17
And b is 2.

1:20
Now, instead of calling 1 + 2,

1:24
which still works, I can call a + b.

1:28
And that will return the two numbers added together.

1:32
If I wanted to, I could also assign that to a third variable.

1:39
Now I have a, b, and c, which is the value of a and b added together.

1:47
Luckily, we're not limited just to addition.

1:51
We could also subtract the two numbers.

1:53
We could do ba.

2:00
And it will return 1.

2:03
We could also add.

2:07
And subtract all at the same time.

2:10
Now, we're not limited to just using whole numbers or integers.

2:15
If we wanted to, we could also work with decimals.

2:20
So we could say 1 + 1.1, and

2:23
Ruby would know how to work with that.

2:29
Go ahead and try experimenting with adding and

2:32
subtracting different numbers and assigning them to variables.
You need to sign up for Treehouse in order to download course files.
Sign up