In this article, we’re going to explore the following topics:
- module scope
- nesting and scopes
First, feel free to have a look to the
Scope Gates in Ruby: Part I.
Before to start
I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1
Please feel free to spread the word and share this post! 🙏
Fun Facts about Ruby — Volume 1
Fun Facts about Ruby — Volume 1 is a collection of cards..
Thank you for your time!
When we use the
- The value of
- The content of the module is embedded in an isolated scope
Let’s have a look at the following example
Here we can see that in our module
self has a different value — it refers to the
Also we don’t have access to variables and methods defined outside the module.
Note that we have access to instance variables in methods for the same reasons described in the Part I.
Nesting and scopes
When we nest a module or a class in another module then:
- the value of
- the content of the nested module is embedded in an isolated scope
- the nested module can’t access local variables from higher scopes
- the nested module can’t access instance variables defined in the nesting scope
Here, the value of
First in the nesting module and
First::Second in the nested module.
Also, we can see the
First::Second module can’t access the
@instance_variable variable defined in the
@instance_variable equals to
nil because it’s a freshly defined instance variable in the
In the Part III, we’ll talk about the notion of Flat Scope and we’ll see how to access higher scopes’ local variables within a class or a module !
I know.. I explained in all the article that we cannot access local variables from out scope within a module or a class.
But Ruby is a permissive language! :-)
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.