2011-04-20 34 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到接收器。