2014-10-04 38 views
0

我寫這個劇本,以更好地瞭解Ruby的self,但我真的不能換我的頭周圍這些語句:對象「主」在Ruby中

def self.test1 
    'test1' 
end 

def test2 
    'test2' 
end 

puts test1 #=> 'test1' 
puts test2 #=> 'test2' 
puts self.test1 #=> 'test1' 
puts self.test2 # test1.rb:12:in `<main>': private method `test2' called for main:Object (NoMethodError) 

如果self.test2不起作用,爲什麼test1?它是否與main對象的行爲有關?

它與單身物件有什麼關係嗎?我知道在Ruby中,當你說def foo.bar時,你是在foo對象上定義一個bar方法?這個事實與關於爲什麼self2.test2失敗的原始問題有什麼關係?

+0

* test1爲什麼?* - 你的意思是「爲什麼'self.test1'」? – sawa 2014-10-04 06:10:33

回答

0

默認情況下,在主對象上定義的實例方法變爲私有方法。雖然你可以重寫。

public def foo; "foo" end 
puts self.foo # => "foo" 

棘手的是,在主環境上定義的類方法可用於主對象。