Search code examples
rubyintegerroman-numerals

Ruby - divmod is returning the correct value, but i'm not understanding why


I am working on the coding kata Roman Numerals defined here. While I have finished it and am not stuck I do have a question that I need help answering.

Here is where my question sits:

class Fixnum
  NUMERALS = [
    ['V', 5], ['IV', 4], ['I', 1]
  ]
  def to_roman
    roman = ""
    number = self
    for key, value in NUMERALS
      count, number = number.divmod(value)
      roman << (key * count)
    end
    roman
  end
end

When I execute divmod on say the number 5, like so

5.to_roman

It returns V. And that makes sense because

5.divmod(5) => 1, 0

But how does this code above not do the same with

5.divmod(1) => 5, 0

So how is it returning V and not IIIII, since it's just appending the key (I) times count (5). Somehow it's obviously correctly returning V instead of IIIII but i'm not sure where that logic is. Any help would be greatly appreciated. Thanks


Solution

  • Your code never executes 5.divmod(1). The first time it executes the loop, key is 'V' and value is 5. It then executes 5.divmod(5) and afterwards, number == 0. So in the next iteration of the loop, when key is 'IV' and value is 4, it executes 0.divmod(4), resulting in count == 0 and nothing being added to the string.

    But this code is weird, because 9.to_roman returns 'VIV'.