Roman numeral converter

In all my years, as a developer, I’ve never had a project that required converting Roman numerals… that project, wherever it is out there in the wild, sounds like it would be an entertaining one..


class RomanNumerals
  DIGITS = {
    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.to_roman(num)
    DIGITS.each_with_object('') do |digits, result|
      result < < digits[1] while num >= digits[0] && num -= digits[0]
    end
  end

  def self.from_roman(string)
    DIGITS.each_with_object([]) do |digits, result|
      result < < digits[0] while string.start_with?(digits[1]) && string[digits[1]] = ''
    end.reduce :+
  end
end
Chapley Watson
Husband, Father, Software Developer, Attempted Writer, and many other things depending on the day.
%d bloggers like this: