A Story About Self.

Intjprogrammer
2 min readFeb 8, 2021

The Studio Ghibli Searcher is a Ruby CLI application that utilizes the Studio Ghibli API and Object Orientation to display data from the API to the user in the terminal. It lists films, characters, and vehicles from the Studio Ghibli universe.

One of the things that helped me quite a lot in building this application was the use of self. So let's dive in and find out what exactly is self and how can it be used!

What is self.? That has no simple answer in Ruby as the notion of what self is can change drastically depending on the context of how it was called. In this case, the context is the scope or environment of which self. is called. Self. grants the programmer access to whatever the current object self is being called on. Which depending on the scope:

The above example is using an Instance method called hello to return self. The return value that you see is the Instance of that class which is an Object.

Self is a powerful tool that can be used to abstract away the need to use arguments in methods as Self. always knows what is being used to call it. One of the earliest uses and advantages of getting used to self is the ability to know the difference between methods and variables. This is especially important to newer Rubyists who can sometimes glaze over code and not be understanding which is which. In Ruby when calling a method you may do so without the use of self. but something to understand is that Ruby secretly always adds it on as a way of abstracting it away so you don’t need to. Early on it can be very important to understand that it’s doing this and that this is a way of alerting to yourself and other programmers that when self. is being called it’s a method and when not, it may be a variable.

Self. can also be used to create and distinguish between instance methods like the example above and class methods which are methods that perform actions on the entire class. Self in this case directs to the class itself instead of just an instance of the class.

After initializing an instance of class Film and dynamically defining getter and setter methods. Self. is used to store the instance and all of its attributes into a class variable set to an array. This showcases the power of self.

This showcases a good few ways into the power and importance of self. It is used to differentiate between variables and methods, to refer to objects based on what called it and the context of its environment. Learning and mastering the use concept of self makes Ruby Object Orientation much more of a joy to use and truly shows the ease and power in programing with objects!

  • Brandon Tyus

INTJProgrammer

--

--