From: Eleanor McHugh Date: 2008-05-08T20:07:12+09:00 Subject: Re: initial stages of scripting On 8 May 2008, at 11:27, Hayden Smith wrote: > Hi there, > I'm a relative newbie when it comes to scripting in ruby however, > for a year 11 project at school, it is necesary for me to program a > maths utilit which requests a user - elementary school aged - to add > to numbers together to reach an answer. I've effected some coding > however, I'm a little stumpt as to why the aplet is not correctly > parsing through the loops. > ===script extract starts== > question = 1 > unless question == 20 > score = 0 > number_of_questions = 0 > num1 = rand(20) > num2 = rand(20) > correct_answer = num1 + num2 > puts("What is #{num1} + #{num2}/?") > user_answer = gets.chomp!.to_i > unless user_answer == correct_answer > puts("Sorry, that is not correct. Please try again.") > user_answer = gets.chomp!.to_i > end > score += 1 > number_of_questions += 1 > question += 1 > puts("Well done! That is correct.\nYou have answered #{score} out of > #{number_of_questions} questions correctly.") > end > exit Hi Hayden, I hope the following answers are helpful. The idiom that you'd be looking to use in your code would be: score = 0 1..20.each do |question| # do stuff end where you keep track of the score yourself as part of do stuff. Although I prefer the form: 1..20.inject(0) |sum, question| # do stuff sum += some_condition ? 1 : 0 end but that requires that the last expression in the block be the one that increments the sum variable. Extra marks if you can write the block without using any local variables ;) Ellie Eleanor McHugh Games With Brains http://slides.games-with-brains.net ---- raise ArgumentError unless @reality.responds_to? :reason