class Converter
NUMERALS = { 50 => "L", 40 => "XL", 10 => "X", 9 => "IX", 5 => "V", 4 => "IV", 1 => "I" }
def convert(number)
return NUMERALS[number] if NUMERALS[number]
to_roman(number)
end
private
def to_roman(number)
result = ""
NUMERALS.each do |value, numeral|
while number >= value
result += numeral
number -= value
end
end
result
end
end
Notice the 40, 9, and 4. These aren't unique numerals, rather they are pairs that represent special subtraction rules. Doing this gets my tests to pass and solves the problem, but I wanted to see if I could come up with a way that better represented how roman numerals work.
Looking for inspiration, I asked twitter and google for some help, but everything I found either used this technique or did some magic number substitution (YUCK). So I set out to find my own solution. Notice I am not professing I set out to find a better solution, only my own, alternative solution.
I won't be showing all of the tests as we go along, but the entire solution was test driven with RSpec. You can review the history and see the tests on github.