What does the % operator do in Ruby in N % 2?

后端 未结 9 1929
甜味超标
甜味超标 2021-02-02 09:57

if counter % 2 == 1 I am trying to decode this line - it\'s a Rails project and I am trying to figure out what the % does in this if statement.

9条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 10:28

    To give a few ways to say it:

    • Modulo operator
    • Remainder operator
    • Modular residue

    Strictly speaking, if a % b = c, c is the unique constant such that

    a == c (mod b) and 0 <= c < b

    Where x == y (mod m) iff x - y = km for some constant k.

    This is equivalent to the remainder. By some well known theorem, we have that a = bk + c for some constant k, where c is the remainder, which gives us a - c = bk, which obviously implies a == c (mod b).

    (Is there a way to use LaTeX on Stackoverflow?)

提交回复
热议问题