...

Ruby programming problem

puts 'Loren'
01-10-2012, 07:25 PM
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

rdspoons
02-21-2012, 09:49 AM
You have the code set to skip variable assignment for your numb_X variables.
So when the print command:
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
is reached you wind up with nil values in the variables.
This happens for any numbers that evaluate to 0 before reaching the last if statement (5,10,20,...50,100,...).

a simple way to correct this is it to add an intial assignment for the variables:
numb_i=numb_v=numb_x=numb_l=numb_c=numb_d=numb_m=0

Here is a version I made following the additional set of rules rules at http://en.wikipedia.org/wiki/Roman_numerals (following the additional set of rules rules at http://en.wikipedia.org/wiki/Roman_numerals).


def ronum n
d=[3000,2000,1000,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1]
r=["MMM","MM","M","CM","DCCC","DCC","DC","D","CD","CCC","CC","C","XC","LXXX","LXX","LX","L","XL","XXX","XX","X","IX","VIII","VII","VI","V","IV","III","II","I"]
rs=""
d.each_with_index {|i,j|
if n.to_i >= d[j]
rs+=r[j]
n=n.to_i-d[j]
end
}
rs
end
puts ronum ARGV.pop


Use (if saved as ronum.rb):
>ronum 1984

result:
MCMLXXXIV

noradibahrehan
06-08-2012, 04:18 PM
1) What will happen when we run the program and explain why ?

n=1
while n <= 15 do
print n.t_s + ' '
n - = 3
end

2) Rewrite the program so that it will run correctly.
3) Produce the output of this program



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum