Understanding `self` in Ruby

A lot of problems faced by beginning Rubyists are caused by not understanding self. In this post we'll take a deep dive into self under conditions both common and uncommon.

Today I'd like to talk about self. If you've been programming Ruby for a while, you've likely internalized the idea of self. Whenever you read or write a program, self is there in the back of your mind.

But for less-experienced Rubyists, self can be baffling. It's always changing, but it's never explicitly shown in the code. You're just expected to know.

A lot of the problems beginners face are caused by not understanding self. If you've ever "lost" an instance variable or puzzled over what data is visible to a mixin, then it's because you didn't understand self in that context.

In this post, we're going to look at self in a variety of every-day situations.

What is self?

You may have heard people say that everything in Ruby is an object. If that's true it means that every piece of code you write "belongs" to some object.

self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere:

  • For instance variables: @myvar
  • For method and constant lookup
  • When defining methods, classes and modules.

In theory, self is pretty obvious. But in practice, it's easy for tricky situations to pop up. That's why I wrote this post.

Examples of self

We're going to step through several examples now. If the first ones seem too basic for you, just keep reading. They get more advanced.

Inside of an instance method

In the code below, reflect is an instance method. It belongs to the object we created via Ghost.new. So self points to that object.

class Ghost
  def reflect
    self
  end
end

g = Ghost.new
g.reflect == g # => true

Inside of a class method

For this example, reflect is a class method of Ghost. With class methods, the class itself "owns" the method. self points to the class.

class Ghost
  def self.reflect
    self
  end
end

Ghost.reflect == Ghost # => true

It works the same with "class" methods inside of modules. For example:

module Ghost
  def self.reflect
    self
  end
end 
Ghost.reflect == Ghost # => true

Remember, classes and modules are treated as objects in Ruby. So this behavior isn't that different from the instance method behavior we saw in the first example.

Inside of a class or module definition

One feature of Ruby that makes it such a good fit for frameworks like Rails is that you can execute arbitrary code inside class and module definitions. When you put code inside of a class/module definition, it runs just like any other Ruby code. The only real difference is the value of self.

As you can see below, self points to the class or module that's in the process of being defined.

class Ghost
  self == Ghost # => true
end 

module Mummy
  self == Mummy # => true
end 

Inside mixin methods

Mixed-in methods behave just like "normal" instance or class methods when it comes to self. This makes sense. Otherwise the mixin wouldn't be able to interact with the class you mixed it into.

Instance methods

Even though the reflect method was defined in the module, its self is the instance of the class it was mixed into.

module Reflection
  def reflect
    self
  end
end 

class Ghost
  include Reflection
end

g = Ghost.new
g.reflect == g # => true

Class methods

When we extend a class to mix in class methods, self behaves exactly like it does in normal class methods.

module Reflection
  def reflect
    self
  end
end 

class Ghost
  extend Reflection
end

Ghost.reflect == Ghost # => true

Inside the metaclass

Chances are you've seen this popular shortcut for defining lots of class methods at once.

class Ghost
  class << self 
    def method1
    end

    def method2
    end
  end
end

The class << foo syntax is actually pretty interesting. It lets you access an object's metaclass - which is also called the "singleton class" or "eigenclass." I plan on covering metaclasses more deeply in a future post. But for now, you just need to know that the metaclass is where Ruby stores methods that are unique to a specific object.

If you access self from inside the class << foo block, you get the metaclass.

class << "test"
  puts self.inspect
end

# => #<Class:#<String:0x007f8de283bd88>

Outside of any class

If you're running code outside of any class, Ruby still provides self. It points to "main", which is an instance of Object:

puts self.inspect # => main
What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Starr Horne

    Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.

    More articles by Starr Horne
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.”
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial