Numbers

Working with integers, decimals, and math

6 min read

Programs are not only about text; they are also about numbers. Ruby makes working with numbers feel just like ordinary arithmetic you already know from school.

Two kinds of numbers

Ruby has two main types of numbers. Whole numbers, like 4 or 100, are called integers. Numbers with a decimal point, like 3.5 or 0.25, are called floats. Ruby figures out which type you mean automatically, just from how you write the number.

age = 12
price = 4.99

Basic math operations

Ruby supports the math symbols you already know, plus a couple of extras.

  • + adds two numbers
  • - subtracts one number from another
  • * multiplies two numbers
  • / divides one number by another
  • % finds the remainder after division
puts 5 + 3
puts 10 - 4
puts 6 * 2
puts 20 / 4
puts 7 % 2

Running this program prints 8, 6, 12, 5, and then 1. That last one, 7 % 2, means "divide 7 by 2 and give me the leftover remainder," which is 1.

Mixing numbers with text

You can use interpolation, which you learned in the last lesson, to combine numbers with words.

age = 12
puts "I am #{age} years old."

This prints "I am 12 years old." Ruby automatically converts the number into text so it can be inserted into the sentence.

A common surprise: integer division

Watch out for dividing two integers. Ruby will drop anything after the decimal point.

puts 7 / 2

This prints 3, not 3.5, because both 7 and 2 are integers. If you want a precise decimal answer, make at least one of the numbers a float, like 7.0 / 2.

Try changing the numbers in the examples above and predicting the answer before you run the code. This is one of the best ways to build number confidence in Ruby.

Quick check

Q1 What does 7 % 2 return in Ruby?

Q2 What does puts 7 / 2 print in Ruby?

Want to save your progress? It's free.

Create a free account