From: "David A. Black" Date: 2009-10-11T02:37:39+09:00 Subject: Re: Trouble with local variables Hi -- On Sun, 11 Oct 2009, Rodrigo Bermejo wrote: > 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. > > read about class variables (or global variables) > @score @score is an instance variable, not a class or global variable. I would definitely encourage everyone to learn about class and global variables, but they're literally about the last thing I would reach for in almost any situation. You definitely won't need them here. David -- The Ruby training with D. Black, G. Brown, J.McAnally Compleat Jan 22-23, 2010, Tampa, FL Rubyist http://www.thecompleatrubyist.com David A. Black/Ruby Power and Light, LLC (http://www.rubypal.com)