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! 🙏

Thank you for your time!

Module Scope

When we use the module keyword:

The value of self changes

changes 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 Commentable module.

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 self changes

changes 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 self is 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 First module.

Indeed, @instance_variable equals to nil because it’s a freshly defined instance variable in the First::Second module

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! :-)

Voilà !