Robert Klemme
11/18/2006 9:07:00 PM
On 18.11.2006 18:16, Robert Klemme wrote:
>> thanks robert. you helped clarify that unfortunately I've i mis-stated
>> the problem, there's a contradiction in my example, what I actually
>> meant was:
>>
>> class X
>> def self.f ; "A" ; end
>> def g ; self.class.f ; end
>> end
>>
>> x = X.new
>> x.g #=> "A"
>>
>> # this should be:
>> class << x
>> def self.f; "B"; end
>> end
>>
>> x.g #=> "A" # want "B"
>>
>> so #respond_to? won't help b/c I didn't intend #f to be instance level
>> method. sorry. what i'm asking for, should make a whole lot more sense
>> now (i hope)
>>
>> thanks,
>> T.
>
>
> Just replace self.class with class<<self;self;end in my code.
>
> robert
>
How about this?
robert
#!/usr/bin/ruby
class Object
# option 1
def dispatch(m,*a,&b)
[class <<self; self; end, self.class].find {|x| x.respond_to? m}.
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(class <<self; self; end, 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"
class << x
def self.f; "B"; end
end
p x.g #=> "A"
p x.h #=> "B"
p x.i #=> "B"