Ruby中的类错误 - NoMethod

时间:2012-02-03 02:47:49

标签: ruby class ruby-1.9

继奶奶问题之后,我想听取他们的建议并将计数器作为一个课程。 Deaf Grandma

这就是我所在的地方

puts 'Say something nice to Grandma.'
puts 'You may need to shout > '

class Counter
  counter = 0
  def Plus
    counter += 1
  end
  def Minus
    counter -= 1
  end
  def Reset
    counter = 0
  end
end

MyCounter = Counter.new

def speaks()
    $speak = gets.strip
    if $speak != 'Bye'
        talk()
    else
        exitPlan()
    end
end

def talk()
    if $speak == $speak.downcase
        puts 'Huh Speak up Sonny'
    else
        year = rand(1930..1951)
        puts 'No not Since ' + year.to_s
    end
        MyCounter.Minus
        if counter < 0
            Counter.reset
        end
        puts 'Say something nice to Grandma'
        speaks()
end

def exitPlan()
    MyCounter.Plus
    unless counter == 3
        puts 'Say something nice to Grandma'
        speaks()
    else
        puts 'good night Sonny'
    end
end
speaks()

这是NoMethod错误

C:\Users\renshaw family\Documents\Ruby>ruby gran2.rb
Say something nice to Grandma.
You may need to shout >
Hi
No not Since 1939
gran2.rb:10:in `Minus': undefined method `-' for nil:NilClass (NoMethodError)
        from gran2.rb:35:in `talk'
        from gran2.rb:22:in `speaks'
        from gran2.rb:52:in `<main>'

1 个答案:

答案 0 :(得分:3)

执行以下操作时:

class Counter
  counter = 0
end

counter是一个局部变量,当你退出类定义时它会消失,这意味着它在以后的任何时候都不存在,因此counter是{ {1}}并且您在执行nil时尝试在-上调用nil,结果为counter -= 1。您似乎要做的是在实例化期间初始化instance variable

NoMethodError

class Counter def initialize @counter = 0 end def plus @counter += 1 end def minus @counter -= 1 end def reset @counter = 0 end end 方法是Ruby中构造函数的名称,并在调用initialize时调用。另请注意,我已将方法名称更改为以小写字母开头,符合惯例:类名称为大写,方法和变量为小写。

我也高度不鼓励使用全局变量(例如Counter.new)。