The Definition Of Nested Module

Nested modules are not what they seem. In this post, Rishi talks about the scope among nested variables. Here’s an Ah-ha! moment for you!

Learning shall never stop..!!!

When we define nested modules like this:

and when we do like this:

Even though both method calls to print_const looks same, and should return same result. But it returns different values of the constant.

When you do this in first case:

and this gives:

So ruby looks for the constant X in the order as A::B::C, A::B, A. and it loads wherever it finds first, and as in our scenario, under module B.

And in second scenario:

and this gives:

Here since the nesting of the module is different, it only search in A::B::C and A, skipping A::B. So it finds constant X under module A.

View original post

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.