Skip to content

Instantly share code, notes, and snippets.

@elreimundo
Last active December 20, 2015 01:49
Show Gist options
  • Save elreimundo/6051518 to your computer and use it in GitHub Desktop.
Save elreimundo/6051518 to your computer and use it in GitHub Desktop.
Here's code that will convert any (properly ordered) roman numeral to a number. It uses a hash, which is something I'm pretty excited about since I don't feel like I totally understand hashes.
def roman_to_integer string
string.upcase!
raise ArgumentError if /[MDCLXVI]*/.match(string).to_s != string
letter_values = {'M' => 1000,
'D' => 500,
'C' => 100,
'L' => 50,
'X' => 10,
'V' => 5,
'I' => 1}
sum = 0
prev_val = 0
numeral_array = string.split('')
while true
if numeral_array.empty?
return sum
end
current_let = numeral_array.pop
if letter_values[current_let] < prev_val
sum -= letter_values[current_let]
else
sum += letter_values[current_let]
end
prev_val = letter_values[current_let]
end
end
@elreimundo
Copy link
Author

Revision two now is not case-sensitive for input

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment