uSource: unsplash.com
Mehdi Farsi
Sep 20 · 2 min read

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

  • scopes and blocks
  • flat scope guard in class/module

First, feel free to browse the Scope Gates in Ruby: Part II article.

Scope and blocks

In Ruby, a block can access outer scope

In this example, we can access the outer_scope_variable variable within our block.

Our block gets access to this variable even though the variable is declared at a main level scope.

In this case, we say that the block flatten scopes.

This is why we commonly call this mechanism: Flat Scope.

In another hand, the block creates an isolated scope — even if the value of self within the block remains the main object.

So we can’t access local variables defined within the block

Here, we can’t access the block_variable from the outer scope.

Now that we’re more familiar with the notion of flat scope let’s see if this notion impacts class definition.

Class, module and block

In Ruby, what you commonly call a class is, behind the scene, an instance of the Class class

Here, we create the Hello and Greeting classes in two different way:

  • using the class keyword
  • we assign an instance of the Class class to the Greeting constant

Note that we are passing a block to the Class.new method.

This block will be interpreted as the content of the class.

Normally a class can’t access variables defined in the outer scope — as the class keyword changes the value of self and creates an isolated scope.

But as we use a block then (normally) we should be able to use the flat scope mechanism

Here we can see that the value of self changes when using the class keyword.

In another hand, our block is still isolated from the main object.

Indeed, as our block is executed in the context of an object then the block flattens scope within this given object — and not with a higher scope as the main object.

That’s why we don’t have access to outer_variable within the Class.new block.

Voilà!

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 an article every 3 days, feel free to follow me to be notified of my new releases.

Mehdi Farsi

Written by

Founder of www.rubycademy.com — I blog about Ruby & ROR - Paris

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