2011-03-10 281 views
0

所以我想我會學一些Ruby。我在和翻譯員一起玩,但我想製作更大的程序,所以我下載了IDE的Aptana。當我嘗試運行此代碼時:爲什麼我不能調用方法?

class HelloWorld 
    def h 
     puts "hello World!" 
    end 
    h 
end 

它給了我一個錯誤,說h是一個未定義的局部變量。當我在解釋器中輸入命令(沒有類的開始和結束)時,它會按照我希望的方式調用h。

我在這裏不知所措。這是怎麼回事?

+2

恭喜要求對堆棧溢出的20000臺紅寶石的問題! – 2011-03-10 05:45:41

回答

0

您的問題是,您在class範圍內發送了h消息。 (我敢肯定,一些人有更多的Ruby經驗將要在這裏糾正我的措辭;還有,如果我完全錯,我向你道歉。)

您可以從另一個實例方法上HelloWorld發送h

class HelloWorld 
    def h; puts "hello world!"; end 

    def g 
    h 
    end 
end 

HelloWorld.new.g 
# => "hello world!" 
+0

你不需要像這樣在g中包裝方法h。您可以省略方法g及其定義,只需通過發出「HelloWorld.new.h」來調用h即可! – RubyFanatic 2011-03-10 05:46:56

+0

當然!我只是向OP顯示如何從類定義中調用方法。 – 2011-03-10 14:56:59

0

試試這個

class HelloWorld 
    def self.h 
    puts "hello World!" 
    end 
    h # you can only call h like this if it is defined as a class method above 
end 

HelloWorld.h # you can call the class method like this also 

您需要定義H作爲一個類的方法調用它這樣。或者,你可以這樣做

class HelloWorld 
    def h 
    puts "hello World!" 
    end 
end 

a = HelloWorld.new # instantiate a new instance of HelloWorld 
a.h 

祝你好運!

+1

在'self.h'示例中,您可以從類內部調用方法'h'。 – 2011-03-10 05:32:21

+0

哦,謝謝......我不知道! – RubyFanatic 2011-03-10 05:35:13

3

定義一個類時,您定義的方法是instance方法。這意味着你會打電話給他們,像這樣:

class HelloWorld 
    def h 
    puts "hello world!" 
    end 
end 

instance = HelloWorld.new 
instance.h 

紅寶石抱怨你的方法不存在,因爲,雖然定義一個類機構,所做的任何函數調用是class方法(或singleton方法)。

如果你真的想這樣做,你會做它像這樣:

class HelloWorld 
    def self.h 
    puts "hello World!" 
    end 
    h 
end