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?
Within an instance method of a class self
refers to that instance. To get the class within an instance you can call self.class
. If you call self
within a class method, you get the class. Inside a class method you can't access any instance of the class.
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
=> #<A:0xacb348c>
1.9.3p194 :156 > a.my_instance_method #5
90544710 #<A:0xacb348c> 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
may be you need :itself method?
1.itself => 1
'1'.itself => '1'
nil.itself => nil
hope this help!
The self
reference is always available, and the object it points to depends on the context.
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
always refers to an instance, but a class is itself an instance of Class
. In certain contexts self
will refer to such an instance.
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
Output:
Hello
#<Hello:0x7ffa68338190>
Hello