Understanding Self in Ruby

Bleak Chandler
3 min readFeb 16, 2021
Photo by Kevin Ku on Unsplash

When I first started learning about “self”, I was a bit baffled. “Self” is, simply put, a Ruby keyword that allows access to the current object. While “self” can be defined with just a few words, it can still be difficult to fully wrap your head around.

Taking a step back, you might recall that everything in Ruby is considered to be an object. Because of that, all code you write belongs to an object. This means that when we create a new class, every instance of that class is an object.

Before we talk more about self, let’s talk about scope. Scope will determine what self means. Wikipedia defines scope as “the range in which a variable can be referenced.” Self always refers to an object’s specific place in Ruby, but that changes depending on where we are in the program.

To illustrate this concept, lets first take a look at two different types of methods, an instance method, and a class method each of these will determine self differently, as the scope is different.

First, consider the below instance method:

class Coffee
def drink

puts self
end
end

To create a new instance of this class, we would use the following code:

new_coffee = Coffee.new

To access the above instance method, we would call new_coffee.drink. In this case, self refers to the instance we created, new_coffee. We know that everything in Ruby is an object, and this applies here, too; self is an object, and in this case, it’s the instance we created, new_coffee.

Image from training.epam.com

Next, let’s take a look at an example of self using a class method. To write a class method, we need to add “self.” to the beginning of the method’s name.

class Coffee
def self.drink

puts self
end
end

In the previous example of self using an instance method, self referred to the object we created, new_coffee, but in this example of a class method, self refers to the class, Coffee. To take a look at self, we’d need to call the class method, using Coffee.drink. This will show us that self is, indeed, the class, Coffee.

Let’s take a look at another example to get a better understanding of self, this time without a class. Consider the below code:

def drink
puts self
end

What happens when we call self without a class? The drink method would print “main. The reason why? The drink method lives outside of a class, so it’s a top-level object. Calling self refers to the main object, which is the top-level object of Ruby; main is an instance of Object.

Image from https://www.pexels.com/photo/text-2004161/

References:

--

--