From: Sean O'Dell Date: 2004-06-22T04:28:04+09:00 Subject: Re: About top-level method On Monday 21 June 2004 11:58, 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. > > 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'm getting more and more confused... > Before I started Ruby, I thought I understood OOP concepts very clearly > (with Java, C#, even Python). > But Ruby puts me in a deep confusion with singleton methods, somewhat > different concept of private/protected accessibility, metaclass, etc... > But I like Ruby very much. > I'm sure that if I overcome the difficulties, I will be a better > programmer...:) Ruby implements global space in a unique way. It secretly puts everything in the top level into the class definition of Object. Try this experiment: @@testvar = "asd" def testvar @@testvar end h = Hash.new p h.send(:testvar) Both testvar and @@testvar are part of the class definition of Object, and Object is the base of all other objects, so that last line of code prints out "asd". Ruby treats everything at the top-level as though it were wrapped by the class definition of Object: class Object # top-level code here end Sean O'Dell