Skip to content

Instantly share code, notes, and snippets.

@katelovescode
Created September 7, 2018 22:20
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 katelovescode/20d6ada6bed8bb1da4d09eeb9e2e446c to your computer and use it in GitHub Desktop.
Save katelovescode/20d6ada6bed8bb1da4d09eeb9e2e446c to your computer and use it in GitHub Desktop.
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