Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SP Ruby quiz - Task 1
$map = {
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1
}
def is_int?(s)
s =~ /^-?[0-9]+$/
end
def to_arabic(s)
output = 0
$map.each do |k, v|
while s.start_with?(k)
output += v
s.slice!(k)
end
end
return output
end
def to_roman(i)
output = ""
$map.each do |k, v|
while i >= v
output << k
i -= v
end
end
return output
end
while input = gets
if is_int?(input)
puts to_roman(input.to_i)
else
puts to_arabic(input)
end
end
@dboesswetter
Copy link

dboesswetter commented Dec 2, 2012

Nice one! Hard-coding the combinations seems to save a lot of code ...

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