Skip to content

Instantly share code, notes, and snippets.

@wisetara
Created August 23, 2017 06:17
Show Gist options
  • Save wisetara/026e28cbb4b9208492551f84546fdd9f to your computer and use it in GitHub Desktop.
Save wisetara/026e28cbb4b9208492551f84546fdd9f to your computer and use it in GitHub Desktop.
Convert Arabic Roman Numbers with Ruby
class Fixnum
# Unique + special roman numerals
ROMANS = { 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' }.freeze
def to_roman
ROMANS[self] || divide_and_conquer_roman(self)
end
private
def divide_and_conquer_roman(number)
ROMANS.reduce('') do | numeral, (arabic, roman) |
quotient, number = number.divmod(arabic)
numeral << roman * quotient
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment