0

What does the % symbol mean in Ruby? For example, I use the following code:

puts "Roosters #{100 - 25 * 3 % 4}"

And get the following output:

97

Where the deuce did the 97 come from? I've looked up what the modulo operator is and still have no idea what it does in this simple mathematics example.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

2 Answers2

2

Modulo operator.

It does division and returns the remainder. So, in your case, 75 / 4 is 18 with a remainder of 3.

25 * 3 = 75

75 % 4 = 3 (the remainder)

100 - 3 = 97

brian
  • 2,745
  • 2
  • 17
  • 33
1

modulo - divide with remainder

divide, and take the remainder from the integer division.

10 / 3 = 3 (with remainder 1 that we discard with integer division)
10 % 3 = 1 (the part we normally discard is the part we are interested in with mod)

It is also used to create cycles. If we had a sequence of 1 to N, we could mod it by M and produce a cycle. Assume M = 3 again

for n in 0..10
   m = n % 3
   puts "#{n} mod 3 = #{m}"
end

0 mod 3 = 0
1 mod 3 = 1
2 mod 3 = 2
3 mod 3 = 0
4 mod 3 = 1
5 mod 3 = 2
6 mod 3 = 0
7 mod 3 = 1
8 mod 3 = 2
9 mod 3 = 0
10 mod 3 = 1
codenheim
  • 20,467
  • 1
  • 59
  • 80