Demystifying Self in Ruby

Your Guide to the Chameleon Keyword

Patrick Karsh
3 min readMar 25, 2024
You know ruby.

In Ruby, understanding the self keyword is crucial for navigating object-oriented programming effectively. Often referred to as a chameleon, self can take on different meanings depending on the context in your code. This article will shed light on this versatile concept and how to use it to your advantage.

What is self?

self is a special keyword in Ruby that always points to the current object. This object can be an instance of a class or the class itself. The meaning of self depends on where it's used in your code. Here's a breakdown of the three main contexts:

Inside an instance method

When you’re within an instance method, self refers to the specific instance of the class that the method is being called on. You can use self to access instance variables and call other instance methods defined within the class.

Inside a class or module definition

Outside of method definitions, but still within a class or module definition, self refers to the class or module itself. This is…

--

--

Patrick Karsh

NYC-based Ruby on Rails and Javascript Engineer leveraging AI to explore Engineering. https://linktr.ee/patrickkarsh