2012-02-03 4 views
0

할머니 질문에 이어 여기서 조언을 듣고 클래스로 카운터를 보완하고 싶습니다.Ruby의 클래스 오류 - NoMethod

class Counter 
    counter = 0 
end 

counter는 지역 변수와 사라집니다 : 당신이 다음 작업을 수행 할 때 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>' 

답변

3

입니다 클래스 정의를 끝낼 때이면 이는 나중에 언제든지 존재하지 않으므로 counternil이고 counter -= 1 일 때 NoMethodError이 될 때 (nil)을 호출하려고합니다. 당신이 뭘하려는 것으로 보인다 것은 인스턴스화하는 동안 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 방법은 루비에서 생성자의 이름, 당신이 Counter.new를 호출 할 때 호출된다. 또한 컨벤션과 마찬가지로 소문자로 시작하는 메소드 이름을 변경했습니다. 클래스 이름은 대문자로, 메소드 및 변수는 소문자입니다.

또한 매우은 전역 변수 (예 : $speak)를 사용하지 않는 것이 좋습니다.