From: Jim Weirich Date: 2004-06-08T02:30:36+09:00 Subject: Re: How to ducktype a Hash? I think the problem Sean is dealing with is one of "type discovery" rather than "type checking". In other words, Sean is getting a stream of objects comming from some outside source (my impression was that it was reconstituted objects from a YAML stream, or something like that). If the object happens to be a container-like object (such as a Hash or an object with hash-like qualities), then Sean wishes to do something specific with those objects. The problem is with the definition of "hash-like". Ruby provides a perfectly fine way of identifying Hashes (e.g. kind_of?(Hash)). It doesn't provide a way of identifying things that are almost (but not quite) hashes. For example, Sean depends on [] and []= (with certain semantics). Someone else noted that they check for each_key. And yet another person recommended checking fetch and store. If an object implements [] and []=, but not each_key, is it hash-like? If it implements fetch and store, but not [], is it hash-like? I think that currently, the concept of hash-like is too vague to be addressed by the language. Sean's method of tagged classes that fit his description is a reasonable compromise in this situation. Here's another idea ... If Sean want to "do_something" with hash like modules, then mixin the following module to any class you consider hash-like ... module HashWork def do_something # Code to do something with hash-like objects end end And add the following ... module Kernel def do_something # DO NOTHING! end end Then, just invoke "do_something" on all your objects. The ones that are hash-like will know what to do... obj.do_something. Now this solution adds a method to existing objects, but I think the main problem with that is just a name clash issue. Make the name of do_something sufficiently unique and you should have no problems. -- -- Jim Weirich jim@weirichhouse.org http://onestepback.org ----------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)