From: Alex Gutteridge Date: 2007-10-02T15:06:00+09:00 Subject: Re: instance variable/ I'm lost On 2 Oct 2007, at 13:14, Erik Boling wrote: > . You can >> just access the @correct variable directly as Bob wrote: >> >> @correct = @correct + 1 > Sorry i dont see where, bob wrote that =|. It is in the first example he gave in his first reply. > ok i understand everyones ways of going about this except bobs ways of > using parameters and returned values is messing me up a bit. So > heres my > finished product, if anyone sees anything usless or somthing im doing > wrong, please let me know :) > > puts 'How many problems do you want to solve?' > problems = gets.chomp > > 5.downto(1) do |x| > puts "The test will beging #{x} in seconds! " > sleep 1 > end > puts 'Start!' > def correct=(correct) > @correct = correct > end > > def correct > @correct > end > @correct = 0 > def multiply > multiple2 = rand(11) > multiple1 = rand(11) > answer = multiple1 * multiple2 > puts 'what is ' + multiple1.to_s + ' * ' + multiple2.to_s + ' ?' > answerp = gets.chomp > if answer.to_s == answerp.to_s > puts "good job" > @correct = @correct + 1 > else puts "You fail!" > end > end > > problems.to_i.times do multiply > end > > puts correct.to_i You still have two methods defined which do (almost) nothing now. You call one of them on the final line, but it isn't necessary because it just returns @correct. Apart from that it is OK, I would rearrange the various to_i and to_s methods and a few other bits to make it (IMO) a bit neater and Ruby-ish: puts 'How many problems do you want to solve?' problems = gets.chomp.to_i 5.downto(1) do |x| puts "The test will begin in #{x} seconds!" sleep 1 end puts 'Start!' @correct = 0 def multiply multiple2 = rand(11) multiple1 = rand(11) answer = multiple1 * multiple2 puts "What is #{multiple1} * #{multiple2} ?" answerp = gets.chomp.to_i if answer == answerp puts "Good job" @correct = @correct + 1 else puts "You fail!" end end problems.times do multiply end puts @correct Again though, I wouldn't use instance variables in this case, but something like this which is slightly longer, but a bit clearer (for me anyway): puts 'How many problems do you want to solve?' problems = gets.chomp.to_i 5.downto(1) do |x| puts "The test will begin in #{x} seconds!" sleep 1 end puts 'Start!' def problem_answered? multiple2 = rand(11) multiple1 = rand(11) answer = multiple1 * multiple2 puts "What is #{multiple1} * #{multiple2} ?" answerp = gets.chomp.to_i if answer == answerp puts "Good job" return true else puts "You fail!" return false end end correct = 0 problems.times do if problem_answered? correct += 1 end end puts correct Alex Gutteridge Bioinformatics Center Kyoto University