From: Paul Brannan Date: 2002-02-14T00:18:46+09:00 Subject: Re: qualms about respond_to? idiom On Wed, Feb 13, 2002 at 11:48:07PM +0900, David Alan Black wrote: > I actually like the look and feel of this better: > > begin > obj.method > rescue NameError > # stuff > end There are at least two problems with this: 1) I may need to do lots of setting up before I ever get around to calling obj.method. 2) obj.method may inadvertently call another method that throws a NameError; thus, getting a NameError does not necessarily mean that obj does not respond to method. I don't like respond_to? either, because just because an object has a method with a particular name doesn't mean that method has the same semantics as I expect it to. Including a mixin to indicate whether an object is *intended* to both implement a particular set of methods and to implement them with particular semantics seems more reasonable. The downside is that you can't extend an arbitrary object just to make it usable with a particular function; instead you must either subclass or use a delegate class. An example of where respond_to? can be a problem is in each(); with an Array, it iterates over the array and yields each element in the array. With a hash, it iterates over the hash and yields each key,value pair. To get hash-like semantics out of an array, I must use each_with_index(), but I can't just figure this out simply by knowing that Array and Hash both respond to each(). Paul