Created
September 6, 2017 14:24
-
-
Save meineerde/3c8dfe497aa616bfaef2af6d41895322 to your computer and use it in GitHub Desktop.
Use Roman numerals the same way you can use other numeric representations in Ruby
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 Module | |
ROMAN_NUMERALS = { | |
'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 | |
}.freeze | |
def const_missing(roman) | |
return super unless roman =~ /\A[MDCLXVI]+\z/ | |
roman.to_s.scan(/C[MD]|X[CL]|I[XV]|[MDCLXVI]/).inject(0) do |sum, numeral| | |
sum + ROMAN_NUMERALS.fetch(numeral) | |
end | |
end | |
end |
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
MCMXCIX == 1_999 | |
# => true | |
MCMXCX == 0x7d0 | |
# => true | |
MCMXCIX + 2 | |
# => 2001 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment