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

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

    Also keep in mind that, Ruby's definition of the modulo (%) operator differs from that of C and Java. In Ruby, -7%3 is 2. In C and Java, the result is -1 instead. In Ruby, the sign of the result (for % operator) is always the same as the sign of the second operand.

    0 讨论(0)
  • 2021-02-02 10:44

    In answer to the question "What does the % symbol do or mean in Ruby?" It is:

    1) The modulo binary operator (as has been mentioned)

    17 % 10 #=> 7 
    

    2) The alternative string delimiter token

    %Q{hello world} #=> "hello world"
    %Q(hello world) #=> "hello world"
    %Q[hello world] #=> "hello world"
    %Q!hello world! #=> "hello world"
    # i.e. choose your own bracket pair
    %q(hello world) #=> 'hello world'
    %x(pwd)         #=> `pwd`
    %r(.*)          #=> /.*/
    

    3) The string format operator (shorthand for Kernel::sprintf)

    "05d" % 123 #=> "00123"
    
    0 讨论(0)
  • 2021-02-02 10:45

    That's the modulo operator. It gives the remainder when counter is divided by 2.

    For example:
    3 % 2 == 1  
    2 % 2 == 0
    
    0 讨论(0)
提交回复
热议问题