If you’re learning Ruby you may find the use of the “self” keyword very confusing.
How does it work?
What is self
, exactly?
It’s a Ruby keyword that gives you access to the current object.
If you don’t know what objects are, watch this video I made for you. It’s related to Object-Oriented Programming.
This “current object” depends on the context.
Context?
Yes, the context is where your Code is at any given moment.
Here’s an example:
If your code is inside an instance method, self
refers to an instance of that class. In other words, it refers to an object.
You can see this in action yourself.
Run this code:
def coffee puts self end coffee # main
This code defines & calls a coffee
method which prints the value of self
.
Why does it print main
?
Because it’s the name of the top-level object, it’s an object where you’ll find all the methods defined outside a class.
Like our coffee
method here.
But if you define a method inside a class named Cat
, then self
would be a Cat
object.
As seen here:
class Cat def meow puts self end end Cat.new.meow # 0x7a14c5>
’
&
’&’
’
’
’…
’’
’
&
’
’
’
&
&:itself
&
&
&