[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

that top-level 'self'

Greg Weeks

11/9/2007 7:07:00 AM

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?
--
Posted via http://www.ruby-....

2 Answers

Trans

11/9/2007 7:25:00 AM

0



On Nov 9, 2:06 am, Greg Weeks <gregwe...@shaw.ca> wrote:
> 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://googl...)

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.


George

11/9/2007 7:32:00 AM

0

On Nov 9, 2007 6:06 PM, Greg Weeks <gregweeks@shaw.ca> wrote:
> 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-t...

Regards,
George.