2012-02-03 36 views
0

繼續從奶奶問題開始,我想在這裏接受他們的建議,並將計數器作爲一個類來使用。 Deaf GrandmaRuby中的類錯誤 - NoMethod

這是我在

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>' 

回答

3

當你做到以下幾點:

class Counter 
    counter = 0 
end 

counter是一個局部變量和消失當你退出類定義,這意味着它在以後的任何時間都不存在,因此counternil,並且您在嘗試在counter -= 1上嘗試呼叫-nil),結果爲NoMethodError。你似乎想要做的就是實例化過程中初始化instance variable

class Counter 
    def initialize 
    @counter = 0 
    end 

    def plus 
    @counter += 1 
    end 

    def minus 
    @counter -= 1 
    end 

    def reset 
    @counter = 0 
    end 
end 

initialize方法是Ruby的構造函數的名稱,當你調用Counter.new被調用。還請注意,我已經將方法名稱更改爲以小寫字母開頭,正如慣例所述:classnames是大寫字母,方法和變量都是小寫字母。

我也高度勸阻使用全局變量(例如$speak)。