Step 4: Math


At the end of the day, all computers are just calculators. So, all of the operations you could perform on numbers using a calculator are available in Ruby.

1 + 1
# => 2
10 - 4
# => 6
-16 + 5
# => -11

In the lines above, the # => lines represent the terminal output from the line above. If you put 1 + 1 into repl.it, the output will be 2. In Ruby, anytime you see a #, the entire line after it is a comment. Most programming languages provide a way for programmers to write comments along with their code in order to tell other programmers (or themselves in the future) what is going on in the code. If you put a # into your code, everything on that line after the # will be treated as a comment and will be ignored by the computer. Here, we are using comments for convenience to show you the terminal output along with the code itself.

In Ruby, the * character is used to represent a multiplication operation:

2 * 2
# => 4
25 * 3
# => 75

Predictably, the / character is used to represent division:

81 / 9
# => 9
30 / 6
# => 5
15 / 4
# => 3

Nope, that last one is not a typo. In Ruby, division between two integers is integer division. With integer division, the remainder of the operation is discarded. Note that this is not a rounding operation - the full remainder is always discarded. So, 9999 / 1000 will return 9, not 10. You can perform division that will return decimals also, but don’t worry about that for now.

You can also perform exponential operations using **:

2 ** 3
# => 8
10 ** 2
# => 100

Another important operator that often goes hand-in-hand with integer division is the modulus operator, %. Modulus gives the remainder of integer division between two numbers:

20 % 2
# => 0
13 % 7
# => 6
42 % 40
# => 2