Last active
December 20, 2015 01:49
-
-
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.
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revision two now is not case-sensitive for input