Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

ruby

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.

like image 715
akkdio Avatar asked Sep 05 '25 09:09

akkdio


1 Answers

% 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.

like image 53
Daniel Vandersluis Avatar answered Sep 08 '25 12:09

Daniel Vandersluis