Understanding the Modulus / Modulo (%)

Hello,

Im new to ruby and Im going through “Learn Ruby the hard way” by Zed A. Shaw and I have a question about the modulus.

There is an exercise with the following lines:

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

And

3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

I understand PE(MD)(AS) but I’m having a trouble wrapping my head around this.

Looking at the first example, irb outputs 97

When I manually do the problem, I get 25 * 3 = 75 - 100 = -25 + 4 = -21. I add 4 because its a remainder from something. This is what I’m misunderstanding.

For the second example, irb gives me 7.

When I try to do it manually, again, I’m not sure how to handle the 2 after the modulus.

I’m fairly certain this is more of a math question that specific to ruby. At the risk of sounding like a complete idiot, I hope that someone can point me in the right direction.

Thanks in advance.

Sudo

Hello Sudo,

Check the Common Student Questions below where you could find a good explanation about how modulus works.

How does % work? Another way to say it is, ”X divided by Y with J remaining.” For example, ”100
divided by 16 with 4 remaining.” The result of % is the J part, or the remaining part.

Hope that answers your question!

Thank you for the response!

I did read that, but was still confused. Im no math scholar but there is no division in the examples above. I get that % refers to a remainder, but from what?

Im trying to logically solve the above math equations so I can understand what Im doing.

I apologize if Im asking for my hand to be held, but could someone please write out the equation and solve it in the same way as irb?

Innumerable appreciations
~sudo

operator precedence:
100 - ((25 * 3) % 4)
100 - (75 % 4)
100 - 3
97

modulus: (75 % 4)
75 - (floor(75 / 4) * 4)
75 - (18 * 4)
75 - 72
3

Thanks Panic. This helped a lot!