Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!!