Para usá-lo, basta chamar o to_roman
método:
2.2.2 (main) > puts 2015.to_roman
MMXV
class Fixnum
def to_roman
Fixnum.roman(self)
end
private
ROMAN_MAP = {
1000 => 'M',
900 => 'CM',
500 => 'D',
400 => 'CD',
100 => 'C',
90 => 'XC',
50 => 'L',
40 => 'XL',
10 => 'X',
9 => 'IX',
5 => 'V',
4 => 'IV',
1 => 'I'
}
def self.roman(n)
# recursion base
return '' if n < 1
# recursive step
tuple = ROMAN_MAP.detect { |decimal, _roman| n >= decimal }
tuple.last + (n - tuple.first).to_roman
end
end