From: Paul Brannan Date: 2002-01-12T01:35:31+09:00 Subject: Re: respond_to? and public/private On Fri, Jan 11, 2002 at 07:43:58PM +0900, Johan Holmberg wrote: > I think the default value of that parameter is a bit unintuitive. > Wouldn't it be better if the default was depending on the call > context ?, ie. that > > ......respond_to? :foo...... > > told if > > ......foo(arguments)...... > > would succeed in finding a callable function/method. This definitely seems like a problem. Your solution makes sense, because if I call respond_to? without an explicit self, then I should be capable of calling foo without an explicit self. > With the current behaviour, I have to be aware of for example that > top-level-functions are implemented as private methods of Object > (or is it Kernel ???). > > My example above includes that I think it would be nice if > respond_to? was sensitive to if it was called with/without an > explicit object reference inside an object method. I don't know how to implement detecting whether one was called with/without an explicit object reference without modifying Ruby source. However, here is a less robust alternative: module RespondTo def respond_to?(meth, priv=nil) priv ||= (self.type == Object ? true : false) super(meth, priv) end end Object.instance_eval { include RespondTo } def foo end p respond_to?(:foo) #=> true class Foo def bar end private def private_bar end end f = Foo.new p f.respond_to?(:foo) #=> false p f.respond_to?(:bar) #=> true p f.respond_to?(:private_bar) #=> false With this change, respond_to? includes private methods by default iff self is an Object and not a subclass of object (which should be sufficient, since most people don't go around instantiating generic Objects). Paul