Pat Maddox
12/17/2006 5:24:00 PM
On 12/17/06, David Vallner <david@vallner.net> wrote:
> Li Chen wrote:
> > Hi all,
> >
> > I add a private method to class Object and try to call it from outside
> > the class. I am confused that it works. Any comments?
> >
> > Thanks,
> >
> > Li
> > ##
> > class Object
> > private
> > def method1(arg1)
> > arg1
> > end
> > end
> >
> > puts "call private method"
> > puts method1(1)
> >
> > ##
> >> ruby variables3.rb
> > call private method
> > 1
> >> Exit code: 0
> >
>
> The toplevel execution context is also an instance of Object. You're
> still inside an instance of the class you've defined #method1 on.
>
> David Vallner
Just to expand on David's point a little...
Since everything is an object in Ruby, you have to be in SOME context
relating to an object. Any time you call a method without an explicit
receiver, the receiver defaults to self. So in that example you end
up calling
self.method1
which is fine, as you'd expect.
Also as you'd expect, instantiating a new Object and then calling the
private method blows up:
irb(main):007:0> o = Object.new
=> #<Object:0x355410>
irb(main):008:0> o.method1
NoMethodError: private method `method1' called for #<Object:0x355410>
from (irb):8
from :0
Pat