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?
Ruby has an answer: the self keyword. Within instance methods, self always refers to the current object.
self is a reserved keyword in Ruby that always refers to the current object and classes are also objects, but the object self refers to frequently changes based on the situation or context. So if you're in an instance, self refers to the instance. If you're in a class, self refers to that class.
One practical use for self is to be able to tell the difference between a method & a local variable. It's not a great idea to name a variable & a method the same. But if you have to work with that situation, then you'll be able to call the method with self. method_name .
In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. Example: @fruit. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.
Class Instances and Instance Methods In Ruby, a class is an object that defines a blueprint to create other objects. Classes define which methods are available on any instance of that class. Defining a method inside a class creates an instance method on that class.
Instance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With