I'm actually working on a static analysis tool that came up against the issue
of modeling Ruby's inclusion semantics recently. The top-level object has
a couple of special behaviors, designed to bring a few of the features of
classes to the top-level in a (hopefully) more intuitive way. If you run:
ruby -e 'p methods(false)'
You'll get:
[:to_s, :public, :private, :include]
to_s just returns "main", and public and private bring visibility to top-level code.
Include is defined (for 1.9.2) at vm.c:968:
static VALUE
top_include(int argc, VALUE *argv, VALUE self)
{
rb_thread_t *th = GET_THREAD();
rb_secure(4);
if (th->top_wrapper) {
rb_warning
("main#include in the wrapped load is effective only in wrapper module");
return rb_mod_include(argc, argv, th->top_wrapper);
}
return rb_mod_include(argc, argv, rb_cObject);
}
The most important line being the most common one, the final one: it simply includes
the given modules into the Object class.
I haven't thought too hard about what the ramifications would be if it were instead
included into the main object's eigenclass, so this answer might not be too satisfying,
but well, there it is.
Cheers,
Mike Edgar
http://carboni.ca/
···
On Feb 2, 2011, at 11:01 PM, Andrew Wagner wrote:
Including AAA at the top level, as in line 7, acts the same as including it
on Object, so every object suddenly has BBB available to it.
This explanation makes sense, and certainly fits the facts. But why is doing
'include' from an irb prompt the same as including the module in Object? If
self points to main, and main is an instance of Object, shouldn't the module
get included into main's eigenclass?