Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert from Roman Numerals to Arabic
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
You can’t perform that action at this time.