From: Pat Maddox Date: 2006-12-18T02:24:13+09:00 Subject: Re: why private is not private On 12/17/06, David Vallner 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 => # irb(main):008:0> o.method1 NoMethodError: private method `method1' called for # from (irb):8 from :0 Pat