From: "Ara.T.Howard" Date: 2004-06-05T13:43:46+09:00 Subject: Re: How to ducktype a Hash? On Sat, 5 Jun 2004, Sean O'Dell wrote: > I need to detect when an object is a hash-like container for other objects, > one which responds to [] and which can index using any object as a value > (string, etc.). > > My problem is, respond_to?(:[]) returns true for objects which are array-like > and for strings (both have [] methods). I need to prevent strings, arrays, > and any other object which responds to :[] from getting to this one point in > code, and only allow a hash or hash-like object. The data type at this > particular point in the code comes from a variety of data sources, and there > are lots of ways it could become a string, or an array or theoretically any > object. I need to know when it's a hash or hash-like object, and raise an > exception when it is not. My biggest problem right now is, when it's a > string or an array, the code has no way of knowing if the returned object/nil > is a valid value, or if a "undesirable" object has slipped in and returned > what it likes to return when you call its [] method. > > So, how do I positively identify when an object is a hash or at least behaves > like a hash? > > Sean O'Dell 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 class MyHashLikeObject include HashingObject def [] k ... end def []= k ... end end now you can simply idx = case obj when HashingObject ... when IndexingObject ... else raise TypeError, obj.class end -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | A flower falls, even though we love it; and a weed grows, even though we do | not love it. --Dogen ===============================================================================