From: Alan Chen Date: 2002-05-23T09:24:45+09:00 Subject: Re: confused about access control On Thu, May 23, 2002 at 08:43:09AM +0900, Ian Macdonald wrote: > Hi, > > I'm rather confused about access control. Observe this: > > irb(main):001:0> class String > irb(main):002:1> protected > irb(main):003:1> def undot! > irb(main):004:2> sub!(/^\.\./, '.') > irb(main):005:2> end > irb(main):006:1> end > nil > irb(main):007:0> class Foo > irb(main):008:1> foo = '..123' > irb(main):009:1> foo.undot! > irb(main):010:1> end > NameError: protected method `undot!' called for "..123":String > from (irb):9 > > Why does this fail? > > The pick-axe book says: > > "Protected methods can be invoked only by objects of the defining > class and its subclasses." > > Well, foo is an instance of String, which is the class that defines > the undot! method, so why does this not work? foo is an instance of String, but Foo isn't a subclass of String. Even if Foo were a subclass of String, foo.undot! is trying to publically access the undot! method. class Bar < String def undot_twice self.undot!.undot! end end bar = Bar.new('....123') bar.undot_twice => '123' -- Alan Chen Digikata LLC http://digikata.com