2010-07-19 29 views
1

在下面的代碼示例中,爲什麼第二個(sheetplus)方法似乎可以獲取實例變量@name和@occupation,但第一個(sheet)方法返回nil?我覺得我錯過了致命的明顯的東西,但我基本上是世界上最糟糕的Ruby程序員。在類方法中,爲什麼一個方法似乎接受實例變量,而另一個方法卻不接受?

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

使用「Tab」鍵! – 2010-07-19 03:03:18

回答

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那麼你會得到作爲sheetplus方法尚不存在的錯誤(sheet尚未運行,以創建)

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

如果你現在打電話sheet它將定義sheetplus方法,並返回定義方法(無)

t.sheet # nil 
的結果

如果你現在打電話sheetplus方法存在所以它成功

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

非常好,謝謝。很高興知道問題背後的原因! – jbfink 2010-07-19 14:54:02

相關問題