Different programming languages use different definitions for (negative) integer division. Ruby uses the one described by Knuth in Concrete Mathematics, p. 82.†
It can be illustrated by an example: let's say we are working with weeks. Our weeks start on Sunday. Numbers are zero-based, so we begin at week 0
, day 0
:
----- 0 -----
0 1 2 3 4 5 6
S M T W T F S
^
If we move forward by 9 days, we are at week 1
, day 2
:
----- 0 ----- ----- 1 -----
0 1 2 3 4 5 6 0 1 2 3 4 5 6
S M T W T F S S M T W T F S
^
These values are returned by /
and %
:
9 / 7 #=> 1
9 % 7 #=> 2
If we move backward by 9 days (from 0), we are at week -2
, day 5
:
---- -2 ----- ---- -1 ----- ----- 0 -----
0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6
S M T W T F S S M T W T F S S M T W T F S
^
Using /
and %
:
-9 / 7 #=> -2
-9 % 7 #=> 5
† There's a funny note on the margin of that page:
Beware of computer languages that use another definition.