From: Jeff Mitchell Date: 2004-06-22T04:47:16+09:00 Subject: Re: About top-level method --- Sam Sungshik Kong wrote: > Hi, Lennon! > > If I understand correctly, one can't call a private method via object name > (receiver). > Private methods can be called only with self. You can also call a private method via send: class A private def f 99 end end puts A.new.send(:f) # => 99 > > So the following code will cause an error (at the top level). > > def foo #->this is a private instance method of Object > ... > end > > obj = Object.new > > obj.foo #->Error, but in irb, it's ok. > > Best explanation so far is that irb makes an exception for debugging > purpose. > > > While trying to find the answer, I met more confusing statements in the > Programming Ruby (Classes and Objects chapter). > > > At the top level, we're executing code in the context of some predefined > object. When we define methods, we're actually creating (private) singleton > methods for this object. Instance variables belong to this object. And > because we're in the context of Object, we can use all of Object's methods > (including those mixed-in from Kernel) in function form. This explains why > we can call Kernel methods such as puts at the top level (and indeed > throughout Ruby): these methods are part of every object. > > > Is the above explanation correct? > Do I create a singleton method if I define a method at the top level? I would say the book explantion is not correct, # courtesy dblack module Kernel def singleton_class class << self self end end end def naked 88 end puts self.class == Object # => true puts self.class.private_instance_methods.include?("naked") # => true puts self.singleton_class.private_instance_methods.include?("naked") # => true If the method was added only to the singleton class, as the book asserts, then first "include?" check would give false. __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail