Scope gates in Ruby: Part I

Mehdi Farsi
Sep 2 · 2 min read

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

  • method scope
  • class scope


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

Voilà !


Feel free to subscribe here:

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.

Here is a link to my last article: Magic comments in Ruby.


E-Learning platform for Ruby and Ruby on Rails

Mehdi Farsi

Written by

Founder of — I blog about Ruby & ROR - Paris


E-Learning platform for Ruby and Ruby on Rails

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade