为什么我得到nil的未定义方法`+':NilClass(NoMethodError)

时间:2016-12-08 21:04:05

标签: ruby

我正在制作游戏,但我遇到了一些问题。我用define来制作一些特殊情况。这是我的定义脚本。

def answerCorrect()
    puts "Correct! Let's proceed to the next question."
    points = points + 1
end

def answerWrong()
    puts "Oh no! That's wrong! Try again!"
    points = points - 2
    input = gets.chomp
end

特例是:

if input == "x"
    answerCorrect()
else
    answerWrong()
end

然而,我收到此错误:

`answerCorrect': undefined method `+' for nil:NilClass (NoMethodError)

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

问题是您的points变量不会在这两种方法中共享。

考虑使用实例变量来管理点系统,即

class AnswerEvaluator
    def initialize
        @points = 0
    end

    def answerCorrect()
        puts "Correct! Let's proceed to the next question."
        @points = @points + 1
    end

    def answerWrong()
        puts "Oh no! That's wrong! Try again!"
        @points = @points - 2
        input = gets.chomp
    end
end

如果您不想直接访问attr_accessor,可以使用@points进行展开。

答案 1 :(得分:1)

问题是该方法不知道"点"是。您可能需要将其设为实例变量@points

示例:

class myGame

     def initialize
         @points = 0
     end

     def answerCorrect()
          puts "Correct! Let's proceed to the next question."
          @points = @points + 1
      end

      def answerWrong()
          puts "Oh no! That's wrong! Try again!"
          @points = @points - 2
          input = gets.chomp
      end
end