From: centrepins@... (Glenn) Date: 2005-02-15T15:14:53+09:00 Subject: Re: Where does this "global code" fit in? Excellent Florian, many thanks! Florian Gross wrote in message news:<37cb91F5c4d56U1@individual.net>... > Glenn wrote: > > > class Window > > #some code here (assume a method "show" is defined somewhere) > > end > > > > w = Window.new #<<< > > w.show #<<< > > > > It's the two lines at the end that confuse me. My natural though is > > they are "global", but in a pure-OO world, they've got to fit into a > > class somewhere? If so, are they actually fitting into (extending) > > class "Object" in some way? Where? How? > > In the Java world they would have to go into a Class. But Ruby is > expression based and more rational -- if you type in code at the top > level it will be executed in the context of a special regular Object > which is called 'main'. It's just a regular Object with a few custom > methods that are just defined for that particular Object (singleton > methods) -- note that it's a regular Object meaning it has the methods > in the Kernel class available to it as well! > > Note that even the definitions of classes and everything else are > executed in that context. Ruby is consistent. > > Here's the list of special methods the top-level Object has: > > > C:\dev.svn\ruby>ruby > > puts methods(false).sort.map { |name| [name, method(name).inspect].join(": ") } > > ^Z > > include: # > > private: # > > public: # > > to_s: # > > include is usually not defined for Objects, but only for Modules. > main.include is equivalent to doing Object.send(:include, ...). > > private and public are usually only for Modules as well, but if you > define a method at the top level it is defined in Kernel. So it does > make sense to be able to overwrite the visibility of these as well. > Default visibility at the top level is private, for Modules it defaults > to public. > > main.to_s just returns 'main'. > > Hope this was of help.