From: Sean O'Dell Date: 2004-06-13T09:55:53+09:00 Subject: Re: How to ducktype a Hash? On Saturday 12 June 2004 16:48, Gavin Sinclair wrote: > On Sunday, June 13, 2004, 3:30:38 AM, Sean wrote: > > On Saturday 12 June 2004 04:23, Rene van Bevern wrote: > >> Sean O'Dell wrote: > >> > So, how do I positively identify when an object is a hash or at least > >> > behaves like a hash? > >> > >> Use the method #to_hash instead. All hash-like objects should be able to > >> give a hash-representation of themselves. > > > > Not necessarily. A database abstraction might act like a hash, but > > wouldn't dump entire tables, which could contain tens of thousands of > > records, as one big Ruby hash. That isn't positive identification. > > Such an abstraction could give a lazy-loading Hash, as in > > class DBAbstraction > def to_hash > Hash.new { |hash, key| > hash[key] = expensive_lookup(key) > } > end > end > > So when you call #to_hash in the first place, it's empty. Each key > you call results in a calculation. All unbeknownst to the user of the > hash. I don't see how this works. When you call to_hash, no arguments are provided, so how could you use the key value there? I've also never seen the block parameter to Hash.new. Not that this changes anything regarding positive identification of a class' purpose, but it's very interesting. Is this all new? My Pragmatic Programmer's Guide must already be far out of date. Sean O'Dell