From: "list. rb" Date: 2009-10-11T01:45:49+09:00 Subject: Re: Trouble with local variables --0016e6476578ac2da70475976d4a Content-Type: text/plain; charset=ISO-8859-1 On Sat, Oct 10, 2009 at 11:58 AM, 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. > -- > Posted via http://www.ruby-forum.com/. > > #checker def correct?(item) letters = %w(A B C D E F G) puts item[:question] + '?' item[:choices].each_with_index {|choice,i| puts "#{letters[i]} - #{choice}" } return item[:solution].call(item[:choices][letters.index(gets.to_s.strip.chomp.upcase)]) rescue false end #setup correct = 0 questions = [ { :question => "Which is the slowest class", :choices => %w(Pyro Demoman Heavy Soldier), :solution => lambda {|input| input == 'Heavy'} }, { :question => "What is the best programming language ever", :choices => %w(whitespace ruby), :solution => lambda {|input| input == 'ruby'} } ] # do work questions.each {|question| correct +=1 if correct? question } #results puts "correct: #{correct}, incorrect: #{questions.size-correct} score: #{correct/questions.size.to_f*100}%" --0016e6476578ac2da70475976d4a--