I just started to teach myself ruby as a first language from Chris
Pines’s book. There is a exercise to write a program that will
translate arabic numbers to old style roman numbers.
I have completed the exercise and my code is works but only if I type
in numbers that are not divisible by 5. As soon I type in a number
divisible by 5 I get the following error: No implicit conversion from
nil to integer (Type error)
I completely stuck.
I would be really grateful if someone could look at my code and
explain what am I doing wrong.
puts ‘Please type in a number that you would like to be translated’
puts ‘to old style Roman number:’
def romnum leftover
var_i = ‘I’
var_v = ‘V’
var_x = ‘X’
var_l = ‘L’
var_c = ‘C’
var_d = ‘D’
var_m = ‘M’
leftover = ''
leftover = gets.chomp
numb_m = leftover.to_i / 1000
leftover = leftover.to_i % 1000
if leftover != 0
numb_d = leftover / 500
leftover = leftover % 500
if leftover != 0
numb_c = leftover / 100
leftover = leftover % 100
if leftover != 0
numb_l = leftover / 50
leftover = leftover % 50
if leftover != 0
numb_x = leftover /10
leftover = leftover % 10
if leftover != 0
numb_v = leftover / 5
leftover = leftover % 5
if leftover != 0
numb_i = leftover /1
leftover = 0
end
end
end
end
end
end
puts var_m * numb_m + var_d * numb_d + var_c * numb_c + var_l *
numb_l + var_x * numb_x + var_v * numb_v + var_i * numb_i
end
romnum 5