Understanding self & how to use it

Christian Bermeo
2 min readSep 22, 2021

What is self?

The keyword self in Ruby refers to the “current object” (default receiver). This object self depends based on the context.

self is initially set to main, the main object is the “top-level” of the program, an instance of the object class that is created when a Ruby program is interpreted.

self in Instance method

In an instance method, self represents the instance itself. More specifically the object itself.

At the time the method definition is executed, the most you can say is that self inside this method will be some future object that has access to this method.

self in Class Method

In the context of a class, in this case, self refers to the current class. Which is simply an instance of the class. Defining a method on self creates a class method.

name_of_movie is a class method of the class of Movie, the class itself owns the method. This self is equivalent to Movie, the class of Movie.

conclusion

self refers to the current object, and classes are also objects. When you are in an instance, self refers to the instance. If you are in a class, self refers to that class.

--

--

Christian Bermeo
0 Followers

Software Engineer Student at Flatiron School