Created
April 11, 2012 17:00
-
-
Save listrophy/2360547 to your computer and use it in GitHub Desktop.
To/From Roman numerals
This file contains 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 | |
def to_roman | |
return '' if self == 0 | |
roman, arabic = { | |
M: 1000, | |
CM: 900, | |
D: 500, | |
CD: 400, | |
C: 100, | |
XC: 90, | |
L: 50, | |
XL: 40, | |
X: 10, | |
IX: 9, | |
V: 5, | |
IV: 4, | |
I: 1 | |
}.detect {|(_,a)| a <= self} | |
roman.to_s + (self - arabic).to_roman | |
end | |
end | |
class String | |
def from_roman | |
return 0 if self == '' | |
roman, arabic = { | |
M: 1000, | |
CM: 900, | |
D: 500, | |
CD: 400, | |
C: 100, | |
XC: 90, | |
L: 50, | |
XL: 40, | |
X: 10, | |
IX: 9, | |
V: 5, | |
IV: 4, | |
I: 1 | |
}.detect {|(r,_)| self =~ /^#{r}/ } | |
arabic + self.sub(/^#{roman}/,'').from_roman | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment