How to find remainder of a division in Ruby?
RubyMathRuby Problem Overview
I'm trying to get the remainder of a division using Ruby.
Let's say we're trying to divide 208 by 11.
The final should be "18 with a remainder of 10"...what I ultimately need is that 10
.
Here's what I've got so far, but it chokes in this use case (saying the remainder is 0
).
division = 208.to_f / 11
rounded = (division*10).ceil/10.0
remainder = rounded.round(1).to_s.last.to_i
Ruby Solutions
Solution 1 - Ruby
The modulo operator:
> 208 % 11
=> 10
Solution 2 - Ruby
If you need just the integer portion, use integers with the /
operator, or the Numeric#div
method:
quotient = 208 / 11
#=> 18
quotient = 208.0.div 11
#=> 18
If you need just the remainder, use the %
operator or the Numeric#modulo
method:
modulus = 208 % 11
#=> 10
modulus = 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
.
Solution 3 - Ruby
please use Numeric#remainder because mod is not remainder
Modulo:
5.modulo(3)
#=> 2
5.modulo(-3)
#=> -1
Remainder:
5.remainder(3)
#=> 2
5.remainder(-3)
#=> 2
here is the link discussing the problem https://rob.conery.io/2018/08/21/mod-and-remainder-are-not-the-same/