If you’re working in Ruby you’ve definitely heard the term “self”. Ruby is an arrogant program and likes to talk about itself an awful lot. Unfortunately, we need to indulge our friend Ruby because it makes our life a whole lot easier. What it does essentially is the exact opposite of this gif:

In short, self gives you access to the object you’re currently working in. It is a reference to the code basically asking “Right this moment while this code is running….. who am I?” That’s it! Why does it require a blog post? Because there’s a lot of cool stuff you can do with it.

Here’s a base-level example of how self works.

class BoomBaby
def boom
self
end

Here we have a class aptly named BoomBaby and an instance method within this class simply called boom that returns self. We can go even simpler than that and keep self at the top-level of your code:

def boom_baby
p self
end

What’s happening is we’re defining an instance method without a class. Since we’re not currently couched in a class, self will refer to something called the main object, or simply “main”. All Ruby is object-oriented, so when we’re not referring to an object specifically, we are referring to “main”.

module BoomGoesTheModule  
def self.look_at_me_please
p self
end
end

And look at that! The self here is referring to either the class we defined or the module we defined earlier, depending on what it’s couched in. This is simply showing that self is a versatile little tool and knows what to refer to.

Self is an incredibly useful tool that will do for you the most important thing something can do for a programmer: make your code shorter. You’ll hear this a lot in your coding journey (like…. seriously you’ll hear it a lot): coders are lazy. If there’s an easier way to do something they will do so. And that’s a good thing! Even in the simple examples above, the code would look much more muddled and harder to read if instead of self we wrote out what self is referring to each time.

And we’ve barely scratched the surface of what self can do for you. You can interpolate it into all sorts of things within instance methods and it will always know that it’s talking about the specific instance at hand or if you’re working with a single source of truth you can initialize a class with certain attributes and then shovel those attributes into that source upon initialization. Here’s an example of the latter:

class BoomestOfBabys

You can come in to clean up other people’s code and they’ll always say :

In conclusion, even though it can be a bit of a confusing concept, I promise it will make your code both more readable and easier to write. If I’m perusing through code I don’t know and my eyeballs pass the word “self”, it’s MUCH easier figuring out what that must be referring to, than seeing a class/instance/module name and having to suss out where that’s coming from.

Self when able. Self responsibly. Self often.

Full time software engineering student at Flatiron School