2011-04-20 50 views
4

什麼時候Ruby自引用對象,什麼時候自引用到Ruby類?用例子來解釋會很棒。沒有得到我的頭在這附近。紅寶石自己在外行方面?

+0

因爲類和模塊都是對象,'self'總是指當前目的。 – 2011-04-20 19:27:09

回答

5

類實際上是對象本身。假設我有一個類Person,這實際上是Class的一個實例。所以你可以自己引用Article的實例,或者你可以自己引用類的實例Article

在最簡單的例子,我能想到的:

class Person 
    def initialize 
    p "Info about Person Instance" 
    p self 
    p self.class 
    end 

    p "Info about Person Class" 
    p self 
    p self.class 
end 


person = Person.new 

它打印:

"Info about Person Class" 
Person 
Class 
"Info about Person Instance" 
#<Person:0x0000010086cf58> 
Person 

想了解更多關於關於自我,I highly recommend read this.

2

我的理解是

  • Environm您正在定義類方法或module_functions,self指的是類/模塊。
  • 在您定義實例方法的環境中,self引用該實例。

例如,

class A 
    def method1 
    self # => instance of A 
    end 
    def self.method2 
    self # => class A 
    endu 
    def A.method3 
    self # => class A 
    end 
end 

class << A 
    def method4 
    self # => class A 
    end 
end 

module B 
    module_function 
    def method5 
    self # => module B 
    end 
end 

例外是instance_evalinstance_exec改變self到接收器。