From: Gavin Sinclair Date: 2004-06-13T11:19:56+09:00 Subject: Re: How to ducktype a Hash? On Sunday, June 13, 2004, 10:55:53 AM, Sean wrote: >> > 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. Try 'ri Hash.new'. All will be explained. Your PragProgGuide certainly is out of date (so is everyone else's, BTW :). It covers Ruby 1.6; Hash.new(&block) was introduced in 1.7/1.8. Note that the above implementation of #to_hash would return a *new* hash every time, thus losing the benefit of any precalculated values. But you clearly get the point. And yes, it is interesting: a very nice example of closures. It would perhaps be nice if all hash-like classes offered this. Gavin