What is the modulo() function in Ruby?

Ruby’s modulo() function returns the remainder of two given numbers that are divided.

Figure 1, below, shows the visual representation of the modulo() function.

Figure 1: Visual representation of modulo() function

Syntax

num_1.modulo(num_2)
# where num_1 and num_2 are the numbers whose modulo is to be calculated
# num_1 % num_2 

Parameter

This function requires another number, (num_2), as a parameter to calculate the modulo.

Return value

This function returns the remainder after the two given numbers are divided.

Code

The following example shows how to use modulo() function in Ruby.

#Both positive numbers
print "(13).modulo(2) : ",(13).modulo(2) , "\n"
#one negative and another positive
print "(16).modulo(-3) : ",(16).modulo(-3) , "\n"
print "(21).modulo(-4) : ",(21).modulo(-4) , "\n"
#fractional number
print "(22.5).modulo(1.6) : ",(22.5).modulo(1.6) , "\n"
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources