George Ogata wrote:
> On 12/8/06, Andreas S <andreas_s / hotmail.com> wrote:
> > Pardon my ignorance. I wasn't aware that the mixin module at top level
> > causes all its methods become globally available for all levels below.
> > Although, some comment on the explanation or reason behind this is
> > appreciated.
>
> At the top level, the "current object", self, is a particular instance
> of Object (which I'll call 'main').
>
> Now, main has some methods in its singleton class.  Let's take a peek:
>
> g@crash:~/tmp$ ruby -e 'p self.methods(false)'
> ["public", "include", "to_s", "private"]
>
> So, when you do "include Foo" at the toplevel, this is, as always, the
> same as "self.include(Foo)", which means call main's singleton class
> method #include.  This is defined to include things into Object.
> Since everything derives from Object, the value of self at any point
> in your code will be an Object, and so you can call Foo's methods
> without a receiver.
>
> Clever, huh?
>
> Along a similar vein, ruby has the notion of the "current class".
> This is like self in that it is defined at any point in your code, but
> there's no short identifier for it.  In fact, I can't think of a
> (non-destructive, thread-safe) expression that will return it.  But
> this is the class that will gain a new method when you do "def foo".

The current class (or module - I saw your correction) is in "self" when
you are outside a "def" or . It is just another object (of class
"Class" or "Module" respectively).

Try this:

class Foo
   p self
   p self.class
end

module Foo
  p self
  p self.class
end

If you are inside a "def" then it is "self.class", but in that case
"self.class" will refer to the class of the object you call the method
on, not the class or module the object was defined in.

Vidar