From: Peter Zotov Date: 2012-07-01T07:10:54+09:00 Subject: Re: Accessor Methods with a Twist Doug Jolley писал 30.06.2012 20:05: > Oh. I see. My knee-jerk reaction from reading the responses was, > "Why > haven't I encountered this issue before?" I think the answer is that > heretofore I have always specified an explicit receiver. So, now I > see. > Thanks very much. > > There is one additional issue. I'm wondering if there is any way > that I > could call these accessor methods from within a module. IOW, it > would > seem to me that I should be able to do something like this: > > @name = 'Doug' > > def name=(name) > @name = name > end > def name() > return @name > end > > module MyModule > def MyModule.get() > puts(some_receiver.name()) > end > end > > MyModule::get() > > I guess the problem is that I don't know what receiver to use. > Thoughts? > > Thanks to all who contributed. > > ... doug Jan E. has replied with an excellent explanation, but I'll answer your question directly. In this case, the receiver you are trying to use is the toplevel object. There is nothing special about the toplevel object except for the fact that it is, well, toplevel--i.e. every code written in a script directly is executed in its context. There is no way to get the toplevel object except for referencing `self' from its context. The code doing that is as follows: module MyModule def MyModule.get(obj) puts(obj.name()) end end MyModule::get(obj) I want to note that the above code is not written with Ruby's common conventions nor is it a good design at all. I have just answered your question, not given you a design advice. Also note that methods defined on toplevel object become available in each Object descendant and not only on the toplevel object itself. E.g. this code will print "A": def print_a puts "A" end Object.new.send :print_a In this case I used method #send, as the default access specifier for the toplevel object is `private' (as opposed to `public' in every other context). -- WBR, Peter Zotov.