[LRUG] Talk topics (Luke Morton)

Steve Tooke steve.tooke at gmail.com
Mon Jun 15 08:08:37 PDT 2015


On Mon, 15 Jun 2015 at 14:10 Carlos Alonso <info at mrcalonso.com> wrote:

>
>
> +1 for 1.
>
> And on that same topic I have a question:
>
> Basically, what's the difference between this code:
>
> module A
>   class B
>   end
> end
>
> and
>
> class A::B
>
> end
>
> I've spotted the difference that the second class could not access any
> constant defined within module A, but what's the point of that second
> syntax? When is it recommended over the above one?
>

:: is the constant lookup operator. It looks-up constants defined within
other constants. This is so that you can gain access to constants which
have been name-spaced.

In ruby, all class and module names are constants - which have been
assigned an instance of the Class or Module class.

In your example above, initially, you have defined the class B inside the
module A. At this point the lexical scope would allow you to refer to any
constants defined inside module B without referring to B and using the ::
operator.

Later you reopen the class A::B (which is its full name-spaced name)
directly, but now the lexical scope of the code is not within the module A.
This is why you would not have access to any other constants defined inside
the module A.

If you try this code:

class C::D
end

You should see it raise a NameError as there is no constant C defined, you
would have to have already declared a C module or constant:

class C
end

class C::D
end

I'm not sure of a good reason to use this form when defining classes? I
wonder if it's a quirk of how the :: operator works, rather than having any
specific use case?

I suppose there could be a use-case when you specifically want to avoid
being in the same lexical scope, but I can't think of a good one and can
imagine it causing confusion later on.

Steve


> Cheers!
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> Archives: http://lists.lrug.org/pipermail/chat-lrug.org
> Manage your subscription: http://lists.lrug.org/options.cgi/chat-lrug.org
> List info: http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20150615/bf517aef/attachment-0003.html>


More information about the Chat mailing list