Skip to content

Instantly share code, notes, and snippets.

@meineerde
Created September 6, 2017 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meineerde/3c8dfe497aa616bfaef2af6d41895322 to your computer and use it in GitHub Desktop.
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
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
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