From: Dave Thomas Date: 2000-10-10T06:24:52+09:00 Subject: [ruby-talk:5355] Re: Object method scope "Morris, Chris" writes: > My question then is this: why are methods that belong to Object > private when prefixed with Self? I don't get this. Hi Chris: I'm coming into this thread late, so I'm probably missing the point, but it's kind of the other way around. A public or protected method can be called by sending a message to a receiver: fred.doSomething The pseudo variable 'self' represents the current object, and so it a valid receiver. If you don't specify a receiver when invoking a method, Ruby sends the message to self. class Dave def method1 puts "m1" end def method2 method1() # these two are self.method1() # the same end end Dave.new.method2 Private methods may not be called with an explicit receiver: they are always called with 'self'. This enforces privacy: they have to be called within the context of the current object. At the top level, methods are added to Object. However, they are added as private methods. This means that they may not be called with a receiver: they always have a receiver of 'self'. Partly this is a practical thing: these methods are probably intended to be called as functions, and so adding a receiver would be silly. Putting them in Object also makes them global, so they're available everywhere. Finally, stopping them from being called with a receiver stops you doing strange things by mistake. For example, if we override Ruby and make a top level method public, we can do some weird things: def wombat puts "Marsupials rule!" end public :wombat wombat # normal call self.wombat # logically same as above 25.wombat # call wombat with an arbitrary receiver def sneaky puts @private end public :sneaky class Dave def initialize @private = 123 end end d = Dave.new d.sneaky # -> 123 So, having these methods private basically makes their use more intuitive. However, Ruby being Ruby, you can always override the default. Enough rope to shoot yourself in the foot ;-) See you Wednesday? Dave