Nested module definitions

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.

Reason:
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

Advertisements

About Gautam Rege

Rubyist, Entrepreneur and co-founder of Josh-Software - one of the leading Ruby development shops in India.
This entry was posted in General. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s