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:'
if leftover != 0
numb_i = leftover /1 # this line will neger get call, so numb_i is nil
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
Also have a look at the Rails Guide on debugging, that will show you
how to use ruby-debug to break into your code and inspect data, which
will help when you have similar issues again.
Even simpler solution is to initialize the variable first. But with
that approach, you should do them all -- the current solution will
barf on the first digit past the one that the number is a multiple of.
(That is, if you feed it 30, it will barf due to var_v being nil; if
you feed it 150, it'll barf due to num_x being nil, etc.)
Another one would be to just output the needed digits immediately,
rather than stashing the number of them and outputting them later.