Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Seth Barthen
Seth Barthen
11,266 Points

Having hard time understanding modulus in Ruby

Hi,

I'm trying to go through and understand how the % sign aka modulus works in Ruby. I understand that it is supposed to give me the remainder of a number after it divides but when I try it in IRB that's not what I'm getting.

For example..

5.0/2 = 2.5

That makes sense so logically if I did the modulus I should get 5, right?

5.0%2 = 1.0

um wut?

Please help explain how this % works!

Thanks

3 Answers

Seth Reece
Seth Reece
32,867 Points

Hi Seth,

% gives you the remainder. 5/2 = 2 with a remainder of 1, so 5%2 = 1.

Hey Seth,

That makes sense so logically if I did the modulus I should get 5, right?

You've made an error in your math. 5 divided by 2 is 2.5. That means 2 goes into 5 evenly 2 times with 1 (read: half of 2) left over. It's easier to model in your head if you think of the modulo process as akin to how you'd solve the problem with pencil and paper.

Seth Barthen
Seth Barthen
11,266 Points

Ah! I got it now, I thought the remainder was the number not how many more times it goes into it. Duh! Thanks guys!!