From: "David A. Black" Date: 2004-06-05T20:55:23+09:00 Subject: Re: How to ducktype a Hash? Hi -- On Sat, 5 Jun 2004, Ara.T.Howard wrote: > is this totally out of the question? > > create a module that is a ducktype 'flag' for hashables > > module HashingObject; end > > add it to hash - a bit ugly, but does nothing > > class Hash; include HashingObject; end > > bless any class you deem good anough with the module [...] > now you can simply > > idx = > case obj > when HashingObject > ... > when IndexingObject > ... > else > raise TypeError, obj.class > end I think that could well work in practice, but wouldn't call it duck typing. You're not asking it to quack up front; you're checking its module ancestry -- which, I hasten to add, may be exactly what you want to do, but isn't the same as what a duck typing approach would lead you to. Let me try to flesh this out with a companion example: class UnHashlikeError < Exception end module Hashlike alias :get_by_key :[] end class Hash # probably inadvisable, as Paul Brannan has include Hashlike # recently pointed out... end # ... value = begin obj.get_by_key(k) rescue NoMethodError raise UnHashlikeError, "Object isn't hashlike" end or something like that. The basic idea here is: get your ducks in a row, so to speak, by manipulating the object universe so that a certain type or subtype of object understands a certain message, then at runtime, send that message and branch on the consequences. David -- David A. Black dblack@wobblini.net