On Sun, Sep 29, 2013 at 10:02 PM, Love U Ruby <lists / ruby-forum.com> wrote:

Xavier Noria wrote in post #1122837:
> > On Sun, Sep 29, 2013 at 4:07 PM, Love U Ruby <lists / ruby-forum.com>
>
> > 3. If the enclosing class or module is a module, check Object
> > explicitly,
> > by hand. That is not the case in the example.
>
> - *If the enclosing class or module is a class* then?
>

In that case the algorithm skips (3) and goes to (4).

Most classes have Object among their ancestors, so the constant will be
found in (2) for the majority of them. Indeed all classes had Object among
their ancestors before 1.9 but with BasicObject that is no longer true.
This introduces a gotcha, for example

    class C < BasicObject
      String # raises NameError
    end

raises NameError, because the String constant belongs to the constants
table of Object, which is not an ancestor of C, and (3) is skipped for
classes. So, NameError. No top-level constant works in that class body
using a relative name, you have to switch to an absolute constant path:

    class C < BasicObject
      ::String # works
    end

Note you must use the leading double colon syntax, this doesn't work:

    class C < BasicObject
      Object::String # raises NameError
    end

because in such constant path the first segment is resolved as a relative
name, only the second and subsequent segments are resolved with the other
algorithm.

That exercise makes apparent that Object is a regular Ruby constant, is not
a global special class or syntax for class names or anything like that,
just an ordinary constant that yields a class object that happens to be
created by the interpreter when it bootstraps.

You can technically remove_const String from Object. Nothing would work,
but you can, they are not special-cased.


 > Let's suppose it was not found.
> >
> > 4. Call const_missing if implemented (this is a method lookup, could be
> > inherited).
> >
>
> I know `const_missing` is a hook method,which is called
> automatically,when constant is not found. But in constant look up why
> does it take into account?
>

Well, for const_missing to do its work someone has to call it :). That
someone is the constant name resolution algorithm.


At Last, Thank you very much for givng your continuous time for helping
> me to climb up the concept ladder.. :)
>

It took me some research to figure all this out and I sympathize with your
curiosity, which is like mine was back in the day :). Very glad to share.