Severin Newsom wrote: > Hello everyone! > I've been coding with Ruby for about three days, and I just ran into my > first big snag. I've been working on a quiz, and the first one had > questions like this: > > puts 'How many classes have a taunt kill?' > puts 'A - Three' > puts 'B - Four' > puts 'C - Five' > puts 'D - Six' > answer = gets.chomp.downcase > if (answer == 'd') > score = score + 1 > else > end > > But it's messy, since I have to repeat the code for every question. (I > know, I know, DRY). With this in mind, I began construction on quiz2, > and used this as my prototype: > > def check > answer = gets.chomp.downcase > if (answer == c_answer) > score = score + 1 > else > puts 'The correct answer was ' + c_answer + '.' > end > end > puts 'Which is the slowest class?' > puts 'A - Pyro' > puts 'B - Demoman' > puts 'C - Heavy' > puts 'D - Soldier' > c_answer = 'c' > check > > I understand the problem (mostly), but I'm looking for a workaround. > Most of my 'fixes' don't work because of the 'A, B, C, D' system; should > that system be changed? > > Sorry for such a long post, I've just really gotten into this. Hey! Making a quiz is not something I have ever done, but after reading your post, this is how I would code it up. #I'd start by making an array with all the right answers to the quiz answer_key = ['a', 'a', 'b', 'd', 'c', 'c'] # for instance # then after printing the question, as you have done above ... answer = [] answer.push(gets.chomp.downcase) #The above places the input into a new element in the array #Once the quiz is complete we can tally the score like this ... answer_key.each_index do |i| score ||= 0 # initialize the variable unless it it already initialized score +=1 if answer_key[i] == answer[i] end puts "You got #{score} answers correct!" # The each_index method of the array class returns the index number for # each element of the array so that you can iterate through both arrays # at once, which is pretty cool, I think. -- Posted via http://www.ruby-forum.com/.