uSource: unsplash.com

Scope Gates in Ruby: Flat Scopes

An overview of the execution context of blocks

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.

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

Thank you for your time!

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

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