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

后端 未结 9 1946
甜味超标
甜味超标 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:34

    This is a very basic question. % is the modulo opereator if counter % 2 == 1 results to true for every odd number and to false for every even number.

    If you're learning ruby you should learn how to use irb, there you can try things out and perhaps answer the question yourself.

    try to enter

    100.times{|i| puts "#{i} % 2 == 1 #=> #{i % 2 == 1}"}
    

    into your irb irb console and see the output, than it should be clear what % does.

    And you really should take a look at the rails api documentation (1.9, 1.8.7, 1.8.7), there you would have found the answer two your question % (Fixnum) with a further link to a detailed description of divmod (Numeric):

    Returns an array containing the quotient and modulus obtained by dividing num by aNumeric. > If q, r = x.divmod(y), then

    q = floor(float(x)/float(y))
    x = q*y + r
    

    The quotient is rounded toward -infinity, as shown in the following table:

     a    |  b  |  a.divmod(b)  |   a/b   | a.modulo(b) | a.remainder(b)
    ------+-----+---------------+---------+-------------+---------------
     13   |  4  |   3,    1     |   3     |    1        |     1
    ------+-----+---------------+---------+-------------+---------------
     13   | -4  |  -4,   -3     |  -3     |   -3        |     1
    ------+-----+---------------+---------+-------------+---------------
    -13   |  4  |  -4,    3     |  -4     |    3        |    -1
    ------+-----+---------------+---------+-------------+---------------
    -13   | -4  |   3,   -1     |   3     |   -1        |    -1
    ------+-----+---------------+---------+-------------+---------------
     11.5 |  4  |   2,    3.5   |   2.875 |    3.5      |     3.5
    ------+-----+---------------+---------+-------------+---------------
     11.5 | -4  |  -3,   -0.5   |  -2.875 |   -0.5      |     3.5
    ------+-----+---------------+---------+-------------+---------------
    -11.5 |  4  |  -3,    0.5   |  -2.875 |    0.5      |    -3.5
    ------+-----+---------------+---------+-------------+---------------
    -11.5 | -4  |   2    -3.5   |   2.875 |   -3.5      |    -3.5
    

    Examples

     11.divmod(3)         #=> [3, 2]
     11.divmod(-3)        #=> [-4, -1]
     11.divmod(3.5)       #=> [3, 0.5]
     (-11).divmod(3.5)    #=> [-4, 3.0]
     (11.5).divmod(3.5)   #=> [3, 1.0]
    

提交回复
热议问题