What does the % operator do in Ruby in N % 2?
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"
That's the modulo operator. It gives the remainder when counter is divided by 2.
For example:
3 % 2 == 1
2 % 2 == 0
%
is the modulo operator. The result of counter % 2
is the remainder of counter / 2
.
n % 2
is often a good way of determining if a number n
is even or odd. If n % 2 == 0
, the number is even (because no remainder means that the number is evenly divisible by 2); if n % 2 == 1
, the number is odd.