What is div() in Ruby?

The div() function in Ruby returns the result of the integer division of two numbers, e.g., dividend/divisor.

Figure 1 shows the visual representation of the div() function.

Figure 1: Visual representation of div() function

Syntax

dividend.div(divisor)

Parameter

This function requires a divisor as a parameter.

If the divisor is zero, then this function throws ZeroDivisionError.

Return value

This function does the integer division of the two numbers and returns its result, e.g., dividend/divisor.

If the result is floating-point, then this function rounds down or takes the floor of the result and gives the integer value.

Example

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

#both positive numbers
print "(15).div(4) : ",(15).div(4), "\n"
#negative dividend
print "(-15).div(6): ",(-15).div(6), "\n"
#zero dividend
print "(0).div(12): ",(0).div(12), "\n"
#fractional numbers and both numbers negative
print "(-15.6).div(-6.7): ",(-15.6).div(-6.7), "\n"

Free Resources