2012-08-22 22 views

回答

40

self总是指一个实例,但一个类本身就是Class的一个实例。在某些情况下,self将涉及这样的实例。

class Hello 
    # We are inside the body of the class, so `self` 
    # refers to the current instance of `Class` 
    p self 

    def foo 
    # We are inside an instance method, so `self` 
    # refers to the current instance of `Hello` 
    return self 
    end 

    # This defines a class method, since `self` refers to `Hello` 
    def self.bar 
    return self 
    end 
end 

h = Hello.new 
p h.foo 
p Hello.bar 

输出:

Hello 
#<Hello:0x7ffa68338190> 
Hello 
+1

不好意思选择这个,但是第一个'p self'实际上是在解析类定义的时候执行的。 'h = Hello.new'实际上会返回与'h.foo'相同的值。我提到这一点是为了防止列出的输出可能误导一些新的Rubyist。 – lilole

5

在类self的实例方法是指该实例。要获得实例中的课程,您可以拨打self.class。如果您在类方法中调用self,您将获得该类。在类方法中,您无法访问该类的任何实例。

3

self引用始终可用,它指向的对象取决于上下文。

class Example 

    self # refers to the Example class object 

    def instance_method 
    self # refers to the receiver of the :instance_method message 
    end 

end 
+0

不要忘记类方法 – ahnbizcad

2

方法self引用它所属的对象。类定义也是对象。

如果您在类定义中使用self,它将引用类定义的对象(对类),如果您在类方法中调用它,它将再次引用该类。

但是在实例方法中,它指的是作为类实例的对象。

1.9.3p194 :145 >  class A 
1.9.3p194 :146?>   puts "%s %s %s"%[self.__id__, self, self.class] #1 
1.9.3p194 :147?>   def my_instance_method 
1.9.3p194 :148?>    puts "%s %s %s"%[self.__id__, self, self.class] #2 
1.9.3p194 :149?>    end 
1.9.3p194 :150?>   def self.my_class_method 
1.9.3p194 :151?>    puts "%s %s %s"%[self.__id__, self, self.class] #3 
1.9.3p194 :152?>   end 
1.9.3p194 :153?>  end 
85789490 A Class 
=> nil 
1.9.3p194 :154 > A.my_class_method #4 
85789490 A Class 
=> nil 
1.9.3p194 :155 > a=A.new 
=> #<A:0xacb348c> 
1.9.3p194 :156 > a.my_instance_method #5 
90544710 #<A:0xacb348c> A 
=> nil 
1.9.3p194 :157 > 

您会看到在类声明期间执行的放置#1。它显示class A是类型为id == 85789490的对象。所以在类声明自我中就是指类。

然后,当类方法被调用(#4)self里面的类方法(#2)再次引用该类。

当调用一个实例方法(#5)时,它显示它内部(#3)self引用该方法所连接的类实例的对象。

如果您需要引用实例方法中使用类self.class

1

可能是你需要:自己的方法?

1.itself => 1 
'1'.itself => '1' 
nil.itself => nil 

希望这有助于!

相关问题