From: Lucas Holland Date: 2007-05-04T20:50:01+09:00 Subject: Re: Top-level Brian Candler wrote: > On Fri, May 04, 2007 at 01:52:21PM +0900, Lucas Holland wrote: >> test >> end >> end >> >> I am able to call the test method because of the implicit receiver, >> self. In this case, however, self refers to the class MyClass (which is >> an instance of Class, as far as I know). > > No. Inside your 'test' method, which is an instance method of MyClass, > self > refers to an object which is one particular instance of MyClass. > > That is, you can't run it like this: > > MyClass.pub > > Rather, you have to do > > MyClass.new.pub > > (the receiver of the message is an *instance* of MyClass that you've > created) > > Outside of 'def test', self does indeed refer to the class. > > class MyClass > p self # self is 'MyClass' > def test > p self # self is an instance of MyClass > end > end Ah, I see. Okay, so I can call puts like a 'standalone function' because of the following: When I run a Ruby script, an object called 'main' is instanciated. It's an instance of the Object class. The Object class includes puts via a mixin from the Kernel module. It's thus like a private instance method of Object. When I call puts, I don't specify a receiver. That's why Ruby takes self as the receiver. At the top level, self refers to the main object. So my call is basically main.puts puts is a *private* instance method of Object, so why can I call it from an instance (main being the instance in this case)? Lucas -- Posted via http://www.ruby-forum.com/.