像`self`这样引用实例的Ruby方法

Ruby中是否有一个方法引用类的当前实例,就像self引用类本身一样?

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 

在类的实例方法中, self指的是该实例。 要在实例中获取类,可以调用self.class 。 如果您在类方法中调用self ,则会获得该类。 在类方法中,您无法访问该类的任何实例。

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 

方法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 => # 1.9.3p194 :156 > a.my_instance_method #5 90544710 # A => nil 1.9.3p194 :157 > 

您会看到在类声明期间执行的放置#1。 它表明class A是Class类型的对象,其id == 85789490。 所以内部类声明self指的是类。

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

并且当调用实例方法时(#5),它表明在其中(#3) self引用该方法所附加的类实例的对象。

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

可能你需要:本身方法?

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

希望这个帮助!