From: Robert Klemme Date: 2006-11-19T01:30:10+09:00 Subject: Re: How to call a class method via the singleton if it exists --------------040804030304020408030202 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit On 18.11.2006 16:56, Trans wrote: > I want to call a class level method from the the instance level, but I > need it to go through the singeton if it exists. Here is the most basic > example: > > class X > def self.f ; "A" ; end > def g ; self.class.f ; end > end > > x = X.new > x.g #=> "A" > > def x.f; "B"; end > x.g #=> "A" > > How do I get the last to return "B"? I know I could use > '(class< a singelton even if doesn't exist, which seems very wasteful. Yet I > don't recall any (non-hack) way to detect if a singleton is defined. Is > there? > > It would be nice if there was a reference with which we could call up > through the class level like this. Two ideas attached. robert --------------040804030304020408030202 Content-Type: text/plain; name="dispatch.rb" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="dispatch.rb" #!/usr/bin/ruby class Object # option 1 def dispatch(m,*a,&b) (respond_to?(m) ? self : self.class). send(m,*a,&b) end # option 2 class Dispatcher def initialize(*a) @a=a end def method_missing(m,*a,&b) @a.each {|o| return o.send(m,*a,&b) if o.respond_to? m} super end end def disp; Dispatcher.new(self, self.class) end end class X def self.f ; "A" ; end def g ; self.class.f ; end def h ; dispatch :f ; end def i ; disp.f ; end end x = X.new p x.g #=> "A" p x.h #=> "A" p x.i #=> "A" def x.f; "B"; end p x.g #=> "A" p x.h #=> "B" p x.i #=> "B" --------------040804030304020408030202--