Created
November 18, 2015 01:06
-
-
Save johaywood/b7d4f8996c103026158d to your computer and use it in GitHub Desktop.
Convert Fixnum to Roman Numeral String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fixnum | |
VERSION = 1 | |
def to_roman | |
numeral = "" | |
numeral << numeral_thousands | |
numeral << numeral_hundreds | |
numeral << numeral_tens | |
numeral << numeral_ones | |
end | |
private | |
def numeral_thousands | |
"M" * (self / 1000) | |
end | |
def numeral_hundreds | |
hundreds = (self % 1000) / 100 | |
if hundreds == 9 | |
"CM" | |
elsif hundreds >= 5 | |
hundreds_numeral = "D" | |
hundreds_numeral << "C" * (hundreds - 5) | |
elsif hundreds == 4 | |
"CD" | |
else | |
"C" * hundreds | |
end | |
end | |
def numeral_tens | |
tens = (self % 100) / 10 | |
if tens == 9 | |
"XC" | |
elsif tens >= 5 | |
tens_numeral = "L" | |
tens_numeral << "X" * (tens - 5) | |
elsif tens == 4 | |
"XL" | |
else | |
"X" * tens | |
end | |
end | |
def numeral_ones | |
ones = self % 10 | |
if ones == 9 | |
"IX" | |
elsif ones >= 5 | |
ones_numeral = "V" | |
ones_numeral << "I" * (ones - 5) | |
elsif ones == 4 | |
"IV" | |
else | |
"I" * ones | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment