Understanding how self
works is critical in reading Ruby code. If you ever feel confused or lost when reading a piece of Ruby code, exam what is self
in the current context might get you back on track. It's one of those things that once you get it, many Ruby codes will start making sense to you.
This article explains:
- what is self
- how to determine self
What Is Self?
Self is a keyword in Ruby representing the default object of the current context.
Being the default object of the current context gives self
two privileges.
- It is the default receiver of messages, meaning calling
a_method
is the same as callingself.a_method
. - It is the owner of instance variables.
The buttermilk pancake belongs to
Pancake
, which is an instance of theClass
object. The banana pancake belongs top1
, which is an instance of thePancake
object. The example shows that, although both instance variables,@my_pancake
, have the same name, they belong to two differentself
and have two different values.
How To Determine Self?
You can determine what is the self
in a context using three simple rules.
- When the current context is outside of any
class
/module
/method
definition,self
ismain
.main
is the built-in top-level default object. - When the current context is inside a
class
/module
definition and outside ofmethod
definitions,self
is theclass
/module
. - When the current context is inside a method definition,
self
is the receiver of the method, the object before.
.
Quiz: what about a top-level method like this one?
Answer: self
is main
in this case because calling puts_self
, is the same as calling self.puts_self
, and in the top_level of the program, self
is main
.
Besides top-level methods and instance methods in a class, there are two other types of methods: instance methods in a module and singleton methods on a specific object. They all follow the same rule: when the current context is inside a method definition, self
is the receiver of the method, meaning the object before .
.
An Instance method in a module:
A singleton method on a specific object:
??You just learned how self
works in Ruby!??
Takeaways
Self
is a keyword in Ruby representing the default object of the current context.Self
is the default receiver of messages and the owner of instance variables.- Three rules for determining
self
: a) when the current context is outside of anyclass
/module
/method
definition,self
ismain
; b) when the current context is inside aclass
/module
definition and outside ofmethod
definitions,self
is theclass
/module
; c) when the current context is inside a method definition,self
is the receiver of the method, the object before.
.
Enjoyed the article?
My best content on Rails, Software Design, and Career in Dev. Delivered weekly.