2010-07-19 2 views
1

다음 코드 예제에서 두 번째 (sheetplus) 메서드는 @name 및 @cupupation 인스턴스 변수를 선택하는 것처럼 보이지만 첫 번째 (sheet) 메서드는 nil을 반환하는 이유는 무엇입니까? 나는 치명적인 것을 놓치고있는 것처럼 느껴진다. 그러나 나는 기본적으로 세계 최악의 루비 프로그래머 다.클래스 메서드에서 한 메서드가 인스턴스 변수를 받아들이는 것처럼 보이고 다른 메서드가 그렇지 않은 이유는 무엇입니까?

class Test 
def initialize(name, occupation) 
    @name = name 
    @occupation = occupation 
def sheet 
    "This is #@name, who is a/an #@occupation" 
def sheetplus 
    "This is #@name, who is a/an #@occupation, but why does this method succeed where the previous one fails?" 
end 
end 
end 
end 
+0

사용 "탭"키를 성공! –

답변

0

직접 붙여 넣은 코드 인 경우 초기화 또는 시트 메서드 정의가 닫히지 않습니다.

class Test 
    def initialize(name, occupation) 
    @name = name 
    @occupation = occupation 
    end 
    def sheet 
    "This is #@name, who is a/an #@occupation" 
    end 
    def sheetplus 
    "This is #@name, who is a/an #@occupation, but why does this method succeed where the previous one fails?" 
    end 
end 

누가 그 시점에서 일어날 수 있는지 알고 있습니다.

0

키워드의 위치가 잘못 되었기 때문입니다. 이것은 예상대로 작동 할 것입니다 :

class Test 
    def initialize(name, occupation) 
    @name = name 
    @occupation = occupation 
    end 
    def sheet 
    "This is #@name, who is a/an #@occupation" 
    end 
    def sheetplus 
    "This is #@name, who is a/an #@occupation, but why does this method succeed where the previous one fails?" 
    end 
end 
1

실제로 이러한 모든 정의를 중첩 했습니까? 아마도 당신은 의미 :

class Test 
    def initialize(name, occupation) 
    @name = name 
    @occupation = occupation 
    end 

    def sheet 
    "This is #{@name}, who is a/an #{@occupation}" 
    end 

    def sheetplus 
    "This is #{@name}, who is a/an #{@occupation}, but why does this method succeed where the previous one fails?" 
    end 
end 
1

다른 사람들이 이미 당신의 문제, 즉 당신이 얻고있는 결과를 얻고있는 이유는 다음이 왜 알고에 관심이 있지만 경우, 잘못된 장소에 ends을 가하고, 무엇 설명했다 .

t = Test.new('Joe', 'Farmer')

이것은 당신의 테스트 클래스의 새 인스턴스를 만듭니다. 이니셜 라이저는 sheet 그것을 만들 실행되지 않은 (지금 sheetplus를 호출 할 경우, 당신은 sheetplus 방법은 아직 존재하지 않기 때문에 오류가 발생합니다 아무것도하지 않는 sheet라는 새로운 방법을 정의하지만 sheetplus

라는 메소드를 정의하고있다)

t.sheetplus 
NoMethodError: undefined method `sheetplus' for 
    #<Test:0x11a9dec @name="Joe", @occupation="Farmer"> 
    from (irb):14 

당신은 지금이 sheetplus 방법을 정의하고 (전무)

t.sheet # nil 
방법을 정의하는 결과를 반환합니다 sheet를 호출하는 경우 당신이 지금하는 방법 sheetplus 호출하면

가 존재 그래서

t.sheetplus 
=> "This is Joe, who is a/an Farmer, but why does this method succeed 
    where the previous one fails?" 
+0

훌륭해, 고마워. 문제의 원인을 알면 좋습니다! – jbfink

관련 문제