class Integer

Constants

COUNT

Public Instance Methods

to_roman() click to toggle source
# File lib/roman_numericals.rb, line 9
def to_roman
  dict = [['I', 'V'], ['X', 'L'], ['C', 'D'], ['M', '']]
  int = self
  roman = ''
  if self <= 0
    raise InvalidNumberError.new("#{self} must be positive integer")
  elsif self >= 4000
    raise InvalidNumberError.new("#{self} must be under 4000")
  end
  COUNT.times do |i|
    div, r = int.divmod(10)
    a, b = dict[i]
    c, d = dict[i + 1]
    case
    when r == 9 then
      roman = "#{a}#{c}#{roman}"
    when r == 4 then
      roman = "#{a}#{b}#{roman}"
    when r >= 5 then
      roman = "#{b}#{a * (r - 5)}#{roman}"
    when r < 4 then
      roman = "#{a * r}#{roman}"
    end
    int = div
  end
  return roman
end