Skip to content

Instantly share code, notes, and snippets.

@listrophy
Created April 11, 2012 17:00
Show Gist options
  • Save listrophy/2360547 to your computer and use it in GitHub Desktop.
Save listrophy/2360547 to your computer and use it in GitHub Desktop.
To/From Roman numerals
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