Ruby method like `self` that refers to instance

前端 未结 5 366
迷失自我
迷失自我 2021-02-02 13:50

Is there a method in Ruby that refers to the current instance of a class, in the way that self refers to the class itself?

5条回答
  •  一整个雨季
    2021-02-02 14:01

    the method self refers to the object it belongs to. Class definitions are objects too.

    If you use self inside class definition it refers to the object of class definition (to the class) if you call it inside class method it refers to the class again.

    But in the instance method it refers to the object which is an instance of the class.

    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 > 
    

    You see puts #1 which executes during class declaration. It shows that class A is an object of type Class with id ==85789490. So inside class declaration self refers to the class.

    Then when class methods is invoked (#4) self inside class method (#2) again refers to that class.

    And when an instance method is invoked (#5) it shows that inside it (#3) self refers to the object of the class instance which the method is attached to.

    If you need to refer the class inside an instance method use self.class

提交回复
热议问题