In this article, we’re going to explore the following topics:
- method scope
- class scope
In Ruby, the scope of a program is strongly correlated to the value of
Here we’re going to detail what are the values of
self when we’re in a method, a class and in the top-level scope.
In Ruby, the top-level scope is the context of the
self refers to the
main object at this moment.
Feel free to read the Ruby Object Model article if you’re not familiar the
Now, what’s the context of
self within a method defined in the top-level scope?
Here we can see that
self also refers to the
The only difference is that we don’t have access to local variables declared in the top-level scope within our method.
This is due to the fact that the
def keyword embeds the content of the method in a completely isolated scope.
However, our method can access instance variables declared in the top-level scope.
Indeed, as instance variables are declared at an object level then we can access these variables in another scope where
self refers to the same object – the
main object in our case.
self points to
main in either the top-level scope and in the method defined in the top-level scope, we can access the
@instance_variable instance variable in the
When we use the
- The value of
- The content of the class is embedded in an isolated scope
Let’s have a look at the following example
Here we can see that in our class
self has a different value — it refers to the
Also we don’t have access to variables and methods defined outside the class.
Note that we have access to instance variables in instance methods for the same reasons described in the first section of the article.
In the Part II & III, we’re going to play with scopes by using modules, nested classes, and blocks (FLAT SCOPES).
ONE MORE THING ⬇
Feel free to subscribe here: www.rubycademy.com
Thank you for taking the time to read this post :-)
Feel free to 👏 and share this article if it has been useful for you. 🚀
Also, as I post a bunch of articles per month.
So feel free to follow me to get a notification when I release an article.
Here is a link to my last article:
Magic comments in Ruby.