How to Do Math with Ruby

Zong-Rong Huang
6 min readOct 8, 2019

--

Ruby comes with useful and highly readable methods to help us do various math operations. Let’s see what we can do with Ruby!

Photo by Émile Perron on Unsplash

Before we start

These methods discussed in this article are applicable to both integers and floating-point numbers (i.e. numbers with decimals).

Since Ruby treats integers and floating-point numbers as different classes, it may perform some implicit coercion in calculation. Here are the general principles:

  • We expect to get an integer when a math equation involves only integers. Example: 4 + 4 #=> 8
  • We expect to get a floating-point number when any number in a math equation has decimals. Example: 4.0 + 4 #=> 8.0

Basic math

Negation

The negation operator - turns a positive number into a negative number and vice versa.

Addition & subtraction

In Ruby we add up two numbers using the + operator, which is the same sign we use in everyday math.

To subtract one number from the other, we use the - operator as in regular math.

Multiplication & division

To multiple one number by another, we use the * operator. To do division, we use the / operator to serve the purpose.

When doing division with integers, as in line 5, Ruby simply returns an integer even though it’s supposed to return a value with decimal digits.

Remainder

To get the remainder of a division statement, we use the % operator between the dividend and the divisor.

This operator is useful, for example, if we want to tell if a number N is an odd or even number by checking if N % 2 == 0.

Power

We use the ** operator to raise a number to a power to simplify repetitive multiplication. The base number is followed by the operator and then by the power.

Operator priority

A math equation can be quite complex since it may involve addition, division, and other math operations. In regular math and Ruby, these operations are not simply processed from left to right: multiplication and division are done prior to addition and subtraction.

Can you figure out the value from the following equation?

Ruby processes 3 * 6 and 4 / 2 first, and then performs subtraction with the two derived numbers. That’s why we get 16 but not 7.

Don’t forget about the % operator. Let’s test if it has higher priority than any previous operator.

From the results of the first four math statements, we find out that calculation is done simply from left to right. This indicates * / and % have the same priority. Yet, from the last two equations, the % operation is always done before the addition and subtraction.

We should also add the ** operator into our test. It turns out to have the highest priority as compared to the other operators.

Now we summarize operator priority in Ruby:

  • High: power (**)
  • Medium: multiplication (*), division (/), and remainder (%)
  • Low: addition (+) and (-)

However, we can force Ruby to do some calculation first by putting high-priority parts into parentheses. Ruby calculates first what’s inside the parentheses and continues with the rest.

Some math methods

Absolute value

Use the .abs method with a number, you get its absolute value, or its distance to zero.

Infinity

Ruby has a way to represent infinity and negative infinity:

The divisor must be 0.0 but not 0 otherwise you get an NaN (aka. not a number) error. Besides, you can’t just type in Infinity or -Infinity to do any calculation in Ruby, which also gives rise to an error:

Square roots & cube roots

Ruby has built-in methods to get the square root and the cube root of a number.

You may notice something unusual of Math.cbrt(27): the returned value is a long floating-point number but not just 3 that we expected. This is caused by number base conversion:

  • In Ruby (and many other programming languages), 10-base numbers are converted to 2-base numbers for computation.

Because of the conversion, an error sneaks in and the final values are not always 100% precise to the original 10-base numbers.

Another way to get the square root and the cube root of a number is using the ** operator. Remember, in the power there must be at least one floating-point number to get the expected result. Otherwise, as in the first equation, the power is calculated to 0 and then the whole equation is calculated to 1. (Any number to the power of 0 is equal to 1).

With the ** operator, you can even get the root of any degree, for example, the root of the fifth degree of 32: 32 ** (1.0 / 5)

Get an approximate number

We do not always need numbers with many decimal digits. A shorter number is sometimes just enough to use. Luckily, in Ruby we can approximate numbers to the desired degree of precision using the following methods.

to_i

By applying the to_i method to a floating-point number, we reserve only its integer value, removing all decimal digits that follow.

.ceil

The .ceil method helps us get the nearest integer that is larger than the specified floating-point number.

.floor

With the .floor method, we get the nearest integer that is smaller than the specified floating-point number.

.round

We get the integer value that is closest to the specified floating-point number using the .round method.

What’s better with .round is that we can specify how many decimal digits to reserve to get a value with enough precision. Let’s say we need two decimal digits. To do so, we just add (2) to the .round method.

Let’s see what happens if you change the number of decimal digits to reserve.

Ruby comes with various ways to let you play around with numbers or do elementary math. One thing that requires our attention is floating-point numbers, as you may have unexpected errors sneaking in.

References:

--

--

Zong-Rong Huang

Frontend web developer/technical writer that writes to learn and self-entertain. I’m based in Taiwan.