1

I am trying to create a CLI arithmetic quiz program and am having difficulty keeping the score within the method. I get the following error message whenever I attempt to increment the score variable (which is declared).

main.rb:17:in `ask': undefined method `+' for nil:NilClass (NoMethodError)
        from main.rb:23:in `<main>'

The code is pasted below. I believe I need to use the 'return' statement to do the increment but I am unsure how this works. (Even if this is not the problem, I'd still welcome any help from anyone to explain how you use boolean return values to count.)

def ask(question, answer)
    print question
    user_answer = gets.chomp
    if user_answer == answer
        puts "Correct!"
        score += 1
    else
        puts "Wrong! The answer was #{answer}"
    end
end

2 Answers 2

2

Your score variable is not declared. You didn't show class implementation, but I suggest you to use attr_writer :score(or attr_accessor :score if you want both get and set var) and set initial value in initialize method.

Sign up to request clarification or add additional context in comments.

Comments

2

All local variables inside a method are visible only within the method. Class variables have greater visibility, so renaming score to @score (both inside and outside the method) should be a remedy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.