When is self really itself?
Edward Smith-Silvia
Posted on March 8, 2021
When is self
really itself? Trick questions, it always is, it's just a matter of who self is. As a newcomer to programming, grasping the concept of self has been challenging as this single variable can have massive impact either making or breaking a program. To me, self has been a riddle understanding where it points and when it should be used. Self can be in reference of the class or to an instance. self is a variable that can be used to point somewhere and when it does, it can change the information that is being received.
Instance
class Dog
def sit
self
end
end
Apollo = Dog.new("Apollo")
Apollo.sit == Apollo
# => true
Shown in the example above, sit
is an instance method. It belongs to the object we created using Dog.new
. In This example we can see that self is pointing to the instance of Dog.
Class
class Dog
def self.sit
self
end
end
Dog.sit == Dog
# => true
In this example, self is pointing to the class. when self comes before the defined method, it changes from an instance method to a class method. Class methods are owned by the class itself.
Other uses for self
Instead of calling a class variable with @@all
, we can call it within a method using self.class.all
with the help of a class method that returns the class variable. Though they function the same, it is the more visually appealing option.
While it should be avoided, if a method and local variable are the same, the method could be called like this.
def cat
"imma cat meow"
end
def method_name
cat = "Munchkin"
puts cat
puts self.cat
end
# => Munchkin
# => imma cat meow
By calling self.cat
, both a method and name are able to be distinguished from one another and be used without confusion to the computer (though it may cause confusion to someone who is reading the code).
While there are more uses that I have seen for self, I am not covering them in this post as I do not wish to teach what I haven't learned and will update this post in the future. If you still struggle to understand self, practice practice practice, it will come with practice. Below are articles which have helped me gain a better understanding of self and I hope they will help you as well.
Happy Coding!
What Is Self in Ruby & How to Use It (Explained Clearly)
Posted on March 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.