On Wed, May 30, 2007 at 11:40:57PM +0900, Maurice Gladwell wrote:
> Brian Candler wrote:
> > In many cases it may be cheaper to attempt the call and to rescue a
> > NoMethodError, than to have 'respond_to?' perform almost as much work as 
> > the
> > call you're testing.
> 
> That's certinly true, but the rescue technique you describe is not a 
> substitute for a working #respond_to?. You're actually sending the 
> message, not asking the object whether it will respond to it.
> 
> These are two completely different operations. The only relevant 
> solution here would be if you aspired to emulate Object#respond_to? by 
> checking if the call raises NoMethodError, but that's infeasible because 
> method call commonly have side effects and/or are destructive.

I'm saying that if you're doing

    object.foo if object.respond_to? :foo

then you may as well do

    object.foo rescue nil

(or a more specific rescue for NoMethodError)

I guess there are other uses for respond_to?, but I very rarely use it -
especially with ActiveRecord, which was the example given. Why do you want
to check that an ActiveRecord class responds usefully to
find_by_foo_and_bar, but not actually call find_by_foo_and_bar?

Regards,

Brian.