From: Patrick Hurley Date: 2005-12-21T13:36:26+09:00 Subject: Re: When are attr_reader type methods called? On 12/20/05, Vivek wrote: > I couldnt get a proper subject for the post but here is my question. > Its regarding methods like > attr_reader defined like below > You can do this in ruby > > # file a.rb > class A > call_this ("hello world") > > def call_this > .... > end > end > > > The A::call_this is called immediately after I run the script.Becuase I > made the method print something and it printed it even though I hadnt > instantiated an object of the class with new. > What if the method uses some instance variables? wouldnt that be a > problem because its called even before an object is created?My question > is at what time during program execution are these methods called? If > there are more than one classes in a file then whats the order ? is it > defined by the language? > My guess is that these are like the equivalent of static member > variables in C, initialized before _main is called.? > Hope to get some clarification on this > vivek > Actually your code will generate an error. You can do this: class Foo def self.bar puts 42 end bar end This will work as the method bar exists and belongs to the class Foo, not an instance of Foo. This will not work: class Boo def hoo puts "Python is nice, but I like Ruby better :-)" end hoo # this will raise a NoMethodError, unless hoo had been defined further up the chain end Of course you can work around much of this with fun method_missing maddness. In the particular case of attr_reader, they are actually part of Module which is the superclass of Class, that is why you can call them inside your class definitions -- they are methods available in Class (and you are defining a Class). pth