 # I need help understanding this small piece of code

Hi,

I have been trying to understand some code found in the “Learn to
Program” book and I’m having a hard time understanding it, I don’t know
if its because I don’t know math (which is true) or I don’t simply
understand
how Ruby is interpreting the code.

//def old_roman_numeral (num)
/////// roman = ‘’
/////// roman = roman + ‘M’ * (num / 1000)
/////// roman = roman + ‘D’ * (num % 1000 / 500)
/////// roman = roman + ‘C’ * (num % 500 / 100)
/////// roman = roman + ‘L’ * (num % 100 / 50)
/////// roman = roman + ‘X’ * (num % 50 / 10)
/////// roman = roman + ‘V’ * (num % 10 / 5)
/////// roman = roman + ‘I’ * (num % 5 / 1)
/////// return roman
//end

puts(old_roman_numeral(1999))

What I don’t know understand are the expressions surrounded with
parenthesis “(num % 1000 / 500) etc”
I do understand that we are passing a parameter when calling the method
and then multiplying the roman letters by this number passed as argument
but, what is… ‘(num % 1000 / 500)’ = WHAT?

(“number” “percentage” 1000 / 500) = WHAT?

Can someone be so kind and explain this a little bit? I know this may
be my math but I don’t see (num % 1000 / 500) being a math equation.

Thanks

On 11/4/2011 09:13, Fily S. wrote:

What I don’t know understand are the expressions surrounded with
parenthesis “(num % 1000 / 500) etc”
I do understand that we are passing a parameter when calling the method
and then multiplying the roman letters by this number passed as argument
but, what is… ‘(num % 1000 / 500)’ = WHAT?

(“number” “percentage” 1000 / 500) = WHAT?

Can someone be so kind and explain this a little bit? I know this may
be my math but I don’t see (num % 1000 / 500) being a math equation.

The % is a modulo operator. It performs integer division like / does
but returns the remainder of the division rather than the quotient.

When you com across something in Ruby you don’t understand, it’s helpful
to open up irb and put in smaller parts of the problem to build your
understanding from the ground up.

-Jeremy

Thanks a lot for the clarification.

Make sense now.

When you com across something in Ruby you don’t understand, it’s helpful
to open up irb and put in smaller parts of the problem to build your
understanding from the ground up.

That’s what I try to do but I could figured this one out, I just didn’t
get it.

Thanks a lot for your help!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.