Skip to content

Instantly share code, notes, and snippets.

@sway
Created December 1, 2012 17:21
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 sway/4183333 to your computer and use it in GitHub Desktop.
Save sway/4183333 to your computer and use it in GitHub Desktop.
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

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