that top-level 'self'

G

Greg Weeks

The ruby top-level 'self' seems like a strange beast. It is an instance
of Object. But definitions of methods, modules, classes, and constants
magically go into the Object class. (So say the reflection methods.)

(In "irb" the methods are public. In "ruby" they are private.)

Can this be understood as less magical?
 
T

Trans

The ruby top-level 'self' seems like a strange beast. It is an instance
of Object. But definitions of methods, modules, classes, and constants
magically go into the Object class. (So say the reflection methods.)
(In "irb" the methods are public. In "ruby" they are private.)

Can this be understood as less magical?

I doubt it. 'main' as it is called, delegates to Object. And it is not
a complete delegation either. Try this...

define_method:)a){}

and you will get a method missing error. Indeed I've run into this
before and created a fix:

require 'facets/main'

It seems silly to have to do this. It' makes more sense to me for main
to be a self extended module instead. the it would not be magical.
While in some respects it may seem convenient to have all top-level
methods wind up in every object, it limits Ruby. For instance, if we
want to use Ruby for quick system scripting, we will be writing a lot
of top-level methods. And funny things can crop up.

require 'open-uri'
def meta; nil; end
open('http://google.com')

NoMethodError: undefined method `status=' for #<StringIO:0xb7a6c374>

No doubt this is due to a poor piece of code in open-uri, but it would
never have been raised here if it weren't for top-level method
injection into Object.

T.
 
G

George

The ruby top-level 'self' seems like a strange beast. It is an instance
of Object. But definitions of methods, modules, classes, and constants
magically go into the Object class. (So say the reflection methods.)

(In "irb" the methods are public. In "ruby" they are private.)

Can this be understood as less magical?

Maybe. Ruby simply has two separate notions of "current object"
(self), and "current class" (the thing which receives method
definitions). This might help:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/228855

Regards,
George.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,811
Messages
2,569,693
Members
45,477
Latest member
IsidroSeli

Latest Threads

Top