Forum: Ruby Using #respond_to? to avoid "no method error" is bad/good practice ?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
5627b1da66c6ce007b5b5409dd2ed364?d=identicon&s=25 Arup R. (my-ruby)
on 2014-02-21 19:14
Sometimes, there is a need, that before calling a method on an object,
we should check, **if the object responds to a method**.

we can do the same either way -

ob.meth if ob.respond_to?(:meth)


ob.meth rescue NoMethodError

Which one is considered as best-practice and why ?
Dave Aronson (Guest)
on 2014-02-21 21:46
(Received via mailing list)
On Fri, Feb 21, 2014 at 1:14 PM, Arup Rakshit <>

> Which one is considered as best-practice and why ?

It depends on the situation, and there are several other ways.  You
can override method_missing to not raise an error, you can use try,
you can use a null object (which certainly keeps the calling code
cleanest), and probably a few others that aren't springing to my mind

This topic is locked and can not be replied to.