What Is Self in Ruby & How to Use It (Explained Clearly)

If you’re learning Ruby you may find the use of the “self” keyword very confusing.

How does it work?

What is self, exactly?

It’s a Ruby keyword that gives you access to the current object.

If you don’t know what objects are, watch this video I made for you. It’s related to Object-Oriented Programming.

This “current object” depends on the context.

Context?

Yes, the context is where your code is at any given moment.

Here’s an example:

If your code is inside an instance method, self is an instance of that class. In other words, self is an object.

You can see this in action yourself.

Run this code:

def coffee
  puts self
end

coffee
# main

This code defines & calls a coffee method which prints the value of self.

Why does it print main?

Because it’s the name of the top-level object, it’s an object where you’ll find all the methods defined outside a class.

Like our coffee method here.

But if you define a method inside a class named Cat, then self would be a Cat object.

As seen here:

class Cat
  def meow
    puts self
  end
end

Cat.new.meow
# <Cat:0x7a14c5>

From these examples, we can tell that the value of self changes depending on where you use it.

Now:

I believe you can understand anything better by understanding its purpose.

Why is self useful?

Let’s look at some examples.

Using Self For Disambiguation

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.

Here’s what I mean:

class Example
  def do_something
    banana = "variable"

    puts banana
    puts self.banana
  end

  def banana
    "method"
  end
end

Example.new.do_something

# "variable"  => puts banana
# "method"    => puts self.banana

Here we have a banana local variable, inside the do_something method, but we also have a banana method.

A local variable takes priority.

That’s why we need to use self here if we want to call the banana method, instead of printing the value of the banana variable.

Next:

Let’s look at a more common use case… Defining class methods!

Using Self To Define Class-Level Methods

Number ONE use for self, without a doubt, is to define class-level methods.

I’m sure you’ve seen them.

These def self.method_name method definitions.

Like this one:

class Salad
  def self.buy_olive_oil
    # ...
  end
end

Salad.buy_olive_oil

This self here is equivalent to Salad, the class name.

Why is this useful?

Because we don’t have to use the class name for each method definition, making our code easier to change if we change the class.

It also makes the code less noisy & better to read.

That’s why we do def self.buy_olive_oil instead of def Salad.buy_olive_oil.

Other Uses For Self

Yes!

There are even more uses for self, so it’s a helpful thing to be familiar with.

For example:

You can use it in a method to compare the current object with another object.

Something like this:

def ==(other)
  self == other
end

You can also use self for debugging purposes, to find out which object you’re working with.

Like this:

p self

Or you can use it as a return value, to implement design patterns like the Builder Design Pattern.

Example:

class Salad
  def initialize
    @ingredients = []
  end

  def add_nuts
    @ingredients << :nuts

    self
  end
end

my_salad = Salad.new.add_nuts

In summary, here's a list of helpful uses for self:

  • Define class-level methods
  • Use an instance method when you have a local variable of the same name
  • Returning Self (builder pattern)
  • Debugging
  • Comparing objects (==)
  • Default receiver of method calls

Self vs Itself

One more thing we should look at before we are done with this topic.

The Kernel#itself method.

It's a method that you can call on an object & the object will return itself.

Example:

[1,2,3,nil].select(&:itself)

# [1, 2 ,3]

This example filters nil & false values.

Understanding the difference:

  • self is a keyword. It's value depends on where you use it
  • itself is a method. It's value depends on what object you use it on (in 1.itself, 1 is the object)

Hope that's helpful.

Conclusion

You have learned about Ruby self keyword, exactly what it is, why it's useful & how to use it.

Now it's your turn to give it a try.

Thanks for reading! πŸ™‚

11 thoughts on “What Is Self in Ruby & How to Use It (Explained Clearly)”

  1. arharhahahrr, I finally understand self, great guide! :), this one had me confused so many times

  2. You have the what and the how but missing the why. Defining class methods is possible because class definition itself is an object, right? And that’s where confusion kicks in πŸ™‚

    • Yes, that’s correct.

      Classes are also objects, when you’re inside a class definition self is the object for the class you’re creating.

  3. Awesome! I love how you explain things so simply. Great for those (like myself) that are just starting to learn about Ruby. Also i love how you mention other relevant information that we can click on and go read about another related aspect!! Que bien!

  4. Thank you, this is an amazing guide. Is there no search feature on this site where I can look up something?

Comments are closed.