Understanding self in Ruby

Written by Bennett on September 25, 2016

Chances are, if you’ve been programming Ruby for a good amount of time, you have likely adopted the whole idea of self. With every program you write, self is always present.

For someone that’s just getting started, the whole idea of self can be sort of hard to internalize. What is self? When should I use self? Do I really need to use self? These are just a few of the questions I would always ask myself whenever I would encounter self while working with Ruby.

What is self?

self is a very interesting concept in the Ruby programming language. Ruby makes sure there is always a self that can be accessed in any given context. Depending on the given context, the value of self will be different.

Examples of self

At the top level context self will identify as main, which is a special instance of object. self will continue to point to main until a class or method is introduced.

puts self
#=> main

puts self.class
#=> Object

Inside a Class

When a class is introduced, the value of self changes. Within a class, self will point to the class object

After we run our program below, we can see that self points to the class that it is defined in.

class Wizard
  self == Wizard

#=> true

Inside a Method

In this example we have a class method being used. spell is a class method that belongs to the Wizard class

With class methods the class itself “owns” the method and self points to the current class.

class Wizard
  def self.spell

Wizard.spell == Wizard
#=> true