From: Rob Biedenharn Date: 2006-06-05T22:58:37+09:00 Subject: Re: Why doesn't method_missing affect respond_to? On Jun 5, 2006, at 8:23 AM, Tim Hunter wrote: > Pat Maddox wrote: >> Take this class: >> >> class Foo >> def method_missing(m, *args) >> m.to_s >> end >> end >> >> irb(main):006:0> Foo.new.foo >> => "foo" >> irb(main):007:0> Foo.respond_to? :foo >> => false >> >> This obviously just returns the name of any method that doesn't exist >> for the object. So if you can send the object any message and get a >> result, why doesn't it respond_to those messages? >> >> Pat > > The respond_to method can't know what method_missing is doing with > missing methods, so it's the up to the class author to provide a > version > of respond_to that agrees with method_missing. More to the point, if you do this: # foo.rb class Foo def method_missing(m, *args) eval "def self.#{m}; '#{m}'; end" self.__send__(m) end end __END__ irb(main):001:0> require 'foo' => true irb(main):002:0> f = Foo.new => # irb(main):003:0> f.respond_to? :foo => false irb(main):004:0> f.foo => "foo" irb(main):005:0> f.respond_to? :foo => true irb(main):006:0> You've now defined a 'foo' method and further invocations of f.foo will go to the newly minted method rather than method_missing each time. -Rob