3.4 Basic Arithmetic Operators

Now that some of the classes that define various data types have been introduced, what can you do with them? Like all other programming languages, Ruby is able to perform many mathematical operations. In Table 3-1, we illustrate how to use Ruby as a calculator.

Table 3-1. Basic arithmetic operators

Symbol

Operation

Example

+

Addition

x = 6 + 2

8

-

Subtraction

x = 3 - 2

1

*

Multiplication

x = 5 * 2

10

/

Division

x = 16/8

2

%

Modulus

x = 5 % 3

2

**

Power

x = 2 ** 4

16

All of the operators listed are binary operators, meaning the operator has two operands. For example, the command A + B is a binary operation, where A and B are the two operands and + is the operator.

When typing mathematical operations in the Ruby interpreter, the order of operations is taken into account. To change the order of operations, use parentheses. Try typing the following in the command line:

irb(main):001:0> x = 10 + 4 / 2

What result did you get? Now try entering the following into the prompt:

irb(main):001:0> x = (10 + 4) / 2

Most of the operators should look familiar. The one that might not is the modulus operator (%). The purpose of this operator is to find the remainder produced by dividing two numbers. For example, 4 modulo 2, abbreviated 4 mod 2, would produce the result 0. This is because 4 / 2 is exactly 2. On the other hand, 2 mod 4 produces a result of 2. This is because 2 / 4 is 0, with a remainder of 2. Let’s try to solve a few easy problems using the modulus ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.