From: Mark Hubbart Date: 2005-05-23T18:12:00+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, Thomas wrote: > > I'm quite shure you don't need to do what you are doing, because this > > violates duck typing > > Thank you very much for pointing out how to use method_missing here. > > BTW I don't think that it "violates" duck typing. The idea is to have a > collection type class with "entrance rules" that can guarantee that > every single element complies with some sort of standard/interface/rule > set/constraints/contracts ... Using kind_of? is only one possible > constraint here. Another one could be respond_to?(:quack). On the long > run, I would like it to look/feel like this: > > class QuackQuack < UniformArray > add_contstraint lambda {|e| e.respond_to?(:quack)} > end > > class ArmyOfDucks < UniformArray > add_contstraint lambda {|e| e.kind_of?(Duck)} > end > > class FlockOfDucks < UniformArray > add_contstraint lambda {|e| e.kind_of?(Duck)} > permit nil # There may be nil values > allow :nested # The array may be nested > end > > d = UniformArray.new > d.add_contstraint lambda {|e| e.kind_of?(Numeric) and e >= 0 and e <= 10} > d.add_handler lambda {|e| e > 10 ? 10 : 0} > > etc. > > I don't think this is incompatible with duck typing. It's just some sort > of specialized collection type of class. 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. On the other hand, if you call it ConstrainedArray and focus on constraints rather than types, it could end up being quite useful... cheers, Mark