Created
September 7, 2018 22:20
-
-
Save katelovescode/20d6ada6bed8bb1da4d09eeb9e2e446c to your computer and use it in GitHub Desktop.
Convert from Roman Numerals to Arabic
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
require "pry" | |
ROMAN_NUMBERS = { | |
"m": 1000, | |
"d": 500, | |
"c": 100, | |
"l": 50, | |
"x": 10, | |
"v": 5, | |
"i": 1 | |
} | |
def convert_roman(string) | |
total = 0 | |
characters = string.split("") | |
characters.each.with_index do |char, idx| | |
if characters[idx + 1] | |
if ROMAN_NUMBERS[char.to_sym] >= ROMAN_NUMBERS[characters[idx + 1].to_sym] | |
total += ROMAN_NUMBERS[char.to_sym] | |
else | |
total -= ROMAN_NUMBERS[char.to_sym] | |
end | |
else | |
total += ROMAN_NUMBERS[char.to_sym] | |
end | |
end | |
total | |
end | |
puts convert_roman("xiv") | |
puts convert_roman("cmxxix") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment