## Wednesday, May 19, 2010

### Modulo operators with respect to Ruby and Javascript

Recently, I was tasked with creating a calendar which transitioned from month to month such as December to January to February, etc.. Also, I needed to go backward on the transition.

A good way to do this is to use a modulo operator. This means that you can figure out which month is the next month number very easily.

So if the month is December, which is month number 12, to find out which month is next:

month = (month % 12) + 1 or (12 % 12 )+ 1, this will work for any month number from 1 to 12.

BUT to go backwards on the month numbers, here is the operation:

month = ((12+(month-2)) % 12) + 1 ... the funny thing is that this operation does not work in Ruby, but it does in Javascript.

In Ruby, here is the equivalent backward operation:

month = ((month-2) % 12) + 1

What is the difference? Why would there be a difference? I have no idea. It seems like Javascript would generate the right response to -1 % 12, which is -1 because 12 divided by -1 is 0 with -1 left over, but Ruby, Python, Perl, and the Google calculator figure that it should be 11 left over. This may be because a negative remainder would make no sense. So if the modulo is negative, then add it to the second operand to get the real modulo.