From: Mark Hubbart Date: 2005-05-24T01:21:13+09:00 Subject: Re: Uniform vector class, inheriting from Array: How to make sure that methods return a Vector and not an Array? On 5/23/05, Jacob Fugal wrote: > On 5/23/05, Mark Hubbart wrote: > > Use of a "uniform" array would seem to preclude duck-typing. Even if > > you use respond_to? instead of kind_of?, it wouldn't catch objects > > that use method_missing to handle messages. For example: > > > > class Wrapper > > def initialize(obj) > > @obj = obj > > end > > def method_missing(*args, &block) > > @obj.__send__ *args, &block > > end > > end > > > > If you use this class to wrap an object, code that relies entirely on > > duck typing will still be able to use the object, even though it won't > > respond_to? much of anything, and it won't be kind_of? the class you > > want. > > Well, on this point, isn't it recommended that whenever you override > method_missing you should also override respond_to? as well so that > they agree? I thought this was in the docs but can't find it now in > either ri method_missing or ri respond_to. Despite that, I know I've > heard it mentioned various times on this list and in general it seems > like a Good Idea. I'd never heard it mentioned on the list (that I remember), but it seems to be mentioned in the style guide, on the rubygarden wiki. No disrespect to those who posted it, but what you see on a wiki doesn't always reflect the views of the entire community. (not that I'm the authority on what this community thinks) Grepping the standard library, I found 24 instances of method_missing being overridden, and 0 instances of respond_to? being overridden: mark@eMac% ruby -e'p ARGF.grep(/def (\S+\.)?method_missing/).size' **/*.rb 24 mark@eMac% ruby -e'p ARGF.grep(/def (\S+\.)?respond_to\?/).size' **/*.rb 0 So, even if the programmer follows that rule, the stdlib doesn't seem to, so you can still get objects creeping in that will respond to a method without raising an error, but don't respond_to? it. cheers, Mark