Scope gates in Ruby: Part I

Tech - RubyCademy
RubyCademy

--

In this article, we’re going to explore the following topics:

  • method scope
  • class scope

Introduction

In Ruby, the scope of a program is strongly correlated to the value of self.

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.

Method scope

In Ruby, the top-level scope is the context of the main object.

Indeed self refers to the main object at this moment.

Feel free to read the Ruby Object Model article if you’re not familiar the main object.

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 main object.

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.

So, as 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 hello method.

Class scope

When we use the class keyword:

  • The value of self changes
  • 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 Hello class.

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 Part II, we’re going to play with scopes by using modules, nested classes, and blocks (FLAT SCOPES).

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.

💚

--

--