In this article, we’re going to explore the following topics:
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 class keyword:
- 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).