Modules as namespaces

I'm sure I'm just missing some finer point of modules as namespaces. But can
someone explain to me why line 26 in http://pastie.org/1418890 gives an
error (uninitialized constant Bar::b::A), but line 25 doesn't? I thought the
two modules would have the same structure. Thanks!

Andrew

I'm sure I'm just missing some finer point of modules as namespaces. But can
someone explain to me why line 26 in http://pastie.org/1418890 gives an
error (uninitialized constant Bar::b::A), but line 25 doesn't? I thought the
two modules would have the same structure. Thanks!

What you are missing is the way Ruby resolves the name of constants.
It first tries to find the constant in the "lexical scope" of the
reference - immediately enclosing module/class, then the next
enclosing module/class, and so on. By defining Bar::B as "class
Bar::B; end" and not "module Bar; class B; end; end" you are changing
the scope in which the constant A should be resolved. You can find out
the modules/classes that are searched by calling Module.nesting
method; see http://pastie.org/1418923

···

--
Anurag Priyam,
3rd Year Undergraduate,
Department of Mechanical Engineering,
IIT Kharagpur.
+91-9775550642

Ah, this makes a lot more sense now, thanks!

···

On Thu, Dec 30, 2010 at 11:07 PM, Anurag Priyam <anurag08priyam@gmail.com>wrote:

> I'm sure I'm just missing some finer point of modules as namespaces. But
can
> someone explain to me why line 26 in http://pastie.org/1418890 gives an
> error (uninitialized constant Bar::b::A), but line 25 doesn't? I thought
the
> two modules would have the same structure. Thanks!

What you are missing is the way Ruby resolves the name of constants.
It first tries to find the constant in the "lexical scope" of the
reference - immediately enclosing module/class, then the next
enclosing module/class, and so on. By defining Bar::B as "class
Bar::B; end" and not "module Bar; class B; end; end" you are changing
the scope in which the constant A should be resolved. You can find out
the modules/classes that are searched by calling Module.nesting
method; see http://pastie.org/1418923

--
Anurag Priyam,
3rd Year Undergraduate,
Department of Mechanical Engineering,
IIT Kharagpur.
+91-9775550642