Scope Gates in Ruby: Part II

Tech - RubyCademy
RubyCademy

--

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.

Module Scope

When we use the module keyword:

  • The value of self 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 Part I.

Nesting and scopes

When we nest a module or a class in another module then:

  • The value of self 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

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--