Hi --

On 5/4/07, Lucas Holland <hollandlucas / gmail.com> wrote:
> 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

Except that Ruby makes a pretty huge distinction between meth and
obj.meth (presence or absence of explicit receiver), namely: private
methods have to be called without an explicit receiver.

  class C
    def x
       puts "x"
    end
    private :x

    def y
       x         # no explicit receiver
    end
  end

  c = C.new
  c.y             # the call to x takes place inside y, where self is c
  c.x             # explicit receiver; Ruby won't let you do it

> puts is a *private* instance method of Object, so why can I call it from
> an instance (main being the instance in this case)?

See above. Private doesn't mean you can never call the method :-)  It
just means that you have to call it without an explicit receiver,
which essentially translates into: you can call private methods on
self (because you can call methods on self without an explicit
receiver).


David

-- 
Upcoming Rails training by Ruby Power and Light:
  Four-day Intro to Intermediate
  May 8-11, 2007
  Edison, NJ
  http://www.rubypal.com/events/05082007