Last active
March 30, 2023 13:42
-
-
Save aseroff/1dacc62a6f11f7eb4a44fd4ddf136996 to your computer and use it in GitHub Desktop.
Convert roman numerals into arabic numerals in place
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 String | |
def to_arabic | |
result = 0 | |
str = self | |
roman_mapping.each_value do |roman| | |
while str.start_with?(roman) | |
result += roman_mapping.invert[roman] | |
str = str.slice(roman.length, str.length) | |
end | |
end | |
result.zero? ? '' : result.to_s | |
end | |
def convert_roman_in_place | |
gsub(/\bM{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\b/m) { |s| s.to_arabic } | |
end | |
private | |
def roman_mapping | |
{ | |
1000 => "M", | |
900 => "CM", | |
500 => "D", | |
400 => "CD", | |
100 => "C", | |
90 => "XC", | |
50 => "L", | |
40 => "XL", | |
10 => "X", | |
9 => "IX", | |
5 => "V", | |
4 => "IV", | |
1 => "I" | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment