Modulus as Handled by Ruby

Education, Programming No Comments

This is an explanation I gave to a student in class today of how the modulus operator behaves in Ruby. As I was writing the explanation down, it all became quite clear to me. I only had a tentative grasp on this concept until trying to explain it. That’s a good feeling when your helping another to understand something gives you clarity on the subject.

Given (-n % x) or (n % -x), the RHS (right hand side) of the modulus operation must be multiplied by the negative integer closest to 0 that will get it past the number on the LHS (left hand side). Then, the result is the difference between this number and the LHS. e.g.:

-7 % 3   # result is 2
# climbing (positive) from -9 (3 * -3) to -7

7 % -3   # result is -2
# dropping (negative) from 9 (-3 * -3) to 7

Of course, when the polarity is the same on both sides, such as (n % x) or (-n % -x), you just multiply the RHS times the positive integer that gets you the closest to the RHS without going past it then the result is the difference between the remainder and the LHS. e.g.:

7 % 3    # result is 1
# climbing (positive) from 6 (3 * 2) to 7

-7 % -3  # result is -1
# dropping (negative) from -6 (-3 * 2) to -7

It might help to note that in Ruby, the RHS always dictates the polarity of the result.