William James
1/2/2007 10:28:00 PM
Shiloh Madsen wrote:
> Ok, I'm having trouble with another exercise in this book. It has
> asked me to write a program that will calculate the old school roman
> numeral value for a given modern number (up to the thousands). To
> clarify, old school roman numerals didn't do the subtraction thing, so
> 4 is IIII, nine is VIIII, etc. I've played around with a few options
> using division, loops and modulus, but can't seem to get my brain
> around the problem...any suggestions?
>
> Shiloh
>
> --
> It is better to rule in hell than serve in heaven.
class Integer
def to_roman
"I =1 V =5 X = 10 L = 50
C = 100 D = 500 M = 1000".
scan( / ([A-Z]) \s *= \s* (\d+) /x ).
map{|letter,val| [ letter, val.to_i ] }.
sort_by{|a| -a.last}.
inject( [ "", self ] ){|roman, pair|
[ roman.first + pair.first * (roman.last / pair.last),
roman.last % pair.last ] }.
first
end
end