CodeNewbie Community 🌱

Cover image for 49 Days of Ruby: Day 6 - Integers
Ben Greenberg
Ben Greenberg

Posted on • Originally published at on

49 Days of Ruby: Day 6 - Integers

Welcome to day 6 of the 49 Days of Ruby! 🎉

In the past few days we have covered variables, strings, introduced ourselves to IRB and a lot more! Today, we are going to learn a bit about another very important data type: Integer.

What is an Integer?

Any number that can be written without a fraction.

In other words, 5, 15, -300, 0, 829304923231231 are all integers. Whereas, 5.3, 0.2, -4.675 are not. What are those latter numbers then? Those fractional numbers are a different data type called a Float.

Integers, like Strings, can be stored inside variables to be referenced later:

drink_order = 1

Enter fullscreen mode Exit fullscreen mode

Did you notice that we did not wrap the 1 in either single or double quotes? If we wrapped it inside quote marks then it would no longer be an Integer, it would become a String.

As an aside, what is the value of "1" + 1?

In some languages, the language itself will fix your math above and either convert the 1 in quote marks into an Integer, or the 1 without quote marks into a String. In the former, the correction would yield 2 as the answer. In the latter, the correction would yield 11 as the answer.

What does Ruby do?

TypeError (no implicit conversion of Integer into String)

Enter fullscreen mode Exit fullscreen mode

Ruby does not automatically fix it for you, but rather returns to you an error. Each error belongs to a group of errors (a Class) that tells you a bit about what type of error it is. In this case, the error is a TypeError because the types of data you are trying to add together do not match.

Back to our new drink_order variable holding the Integer 1. If you recall, yesterday we created a customer named Ben with a favorite drink of Iced Americano. We then printed that data out using string interpolation.

We can do the same thing here with our Integer!

"Hi, #{name}! Welcome back! Would you like to order another #{favorite_drink}? You previously ordered it #{drink_order} times.

Enter fullscreen mode Exit fullscreen mode

This would output the following:

Hi, Ben! Welcome back! Would you like to order another Iced Americano? You previously ordered it 1 times.

We see that you can interpolate an Integer into a new String, just like other Strings.

Another important item to know about Integers is how they interact with Floats. Remember from above that a Float is a fractional number, like 5.2, for example.

What happens if we try to add 3 + 5.2?

2.5.1 :002 > 3 + 5.2
 => 8.2 

Enter fullscreen mode Exit fullscreen mode

The return value is a new Float: 8.2.

That's it for today! Tomorrow we will explore Booleans!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Oldest comments (0)