How to find remainder of a division in Ruby?
If you need just the integer portion, use integers with the /
operator, or the Numeric#div
method:
quotient = 208 / 11#=> 18quotient = 208.0.div 11#=> 18
If you need just the remainder, use the %
operator or the Numeric#modulo
method:
modulus = 208 % 11#=> 10modulus = 208.0.modulo 11#=> 10.0
If you need both, use the Numeric#divmod
method. This even works if either the receiver or argument is a float:
quotient, modulus = 208.divmod(11)#=> [18, 10]208.0.divmod(11)#=> [18, 10.0]208.divmod(11.0)#=> [18, 10.0]
Also of interest is the Numeric#remainder
method. The differences between all of these can be seen in the documentation for divmod
.
please use Numeric#remainder because mod is not remainder
Modulo:
5.modulo(3)#=> 25.modulo(-3)#=> -1
Remainder:
5.remainder(3)#=> 25.remainder(-3)#=> 2
here is the link discussing the problemhttps://rob.conery.io/2018/08/21/mod-and-remainder-are-not-the-same/