From: "David A. Black" Date: 2008-06-01T06:59:31+09:00 Subject: Re: Class Module Hi -- On Sun, 1 Jun 2008, Wesley Silva wrote: > Hi, I'm still learning ruby and i'm trying, but I just can't understand > this result... > > class Module > @@docs = {} > # Invoked during class definitions > def doc(str) > @@docs[self.name] = self.name + ":\n" + str.gsub(/^\s+/, '') > end > # invoked to get documentation > def Module::doc(aClass) > # If we're passed a class or module, convert to string > # ('<=' for classes checks for same class or subtype) > aClass = aClass.name if aClass.class <= Module > @@docs[aClass] || "No documentation for #{aClass}" > end > end > class Example > doc("This is a sample documentation string") > > # .. rest of class > end > > puts Module::doc(Example) > > > Produces: > > Example: > This is a sample documentation string > > > But > > class Module > @@docs = {} > # Invoked during class definitions > def doc(str) > @@docs[self.name] = self.name + ":\n" + str.gsub(/^\s+/, '') > end > # invoked to get documentation > def Module::doc(aClass) > # If we're passed a class or module, convert to string > # ('<=' for classes checks for same class or subtype) > aClass = aClass.name if aClass.class <= Module > @@docs[aClass] || "No documentation for #{aClass}" > end > end > class Example doc("This is a sample documentation string") > > # .. rest of class > end > > puts Module::doc(Example) > > Produces: > > No documentation for Example > > > Can anybody tell me why? When you do this: class Example < Module doc("string") end the doc method you're calling is Module.doc. The object Example has two doc methods in its method lookup path, and that's the one it hits first. If you change Module.doc to Module.show_doc (or whatever), you'll see the difference. David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin See http://www.rubypal.com for details and updates!