From: dblack@... Date: 2007-03-02T11:22:14+09:00 Subject: Re: Duck Typing Hash-Like Objects Hi -- On Fri, 2 Mar 2007, Jacob Fugal wrote: > On 3/1/07, Gary Wright wrote: >> My question is: What is the least constraining test to determine >> if you've got a hash-like object? Is arg.respond_to?(:has_key?) >> reasonable? At first I thought a test for :[] would be great but >> that catches strings also. I'm thinking that if someone hands my >> method a Hash or a HashWithIndifferentAccess or an OrderedHash or >> a tree of some sort, I'd like to be able to accept all of them. > > I'd do it like this: > > def foo(duck) > # if the duck claims to have keys and indexing, we'll just use it as > is > unless duck.respond_to?(:keys) and duck.respond_to?(:[]) > # otherwise, we'll ask it to turn itself into a hash for us > if duck.responds_to?(:to_hash) > duck = duck.to_hash > else > # not close enough to a hash... > raise ArgumentError, "want something with keys and indexing, > or that supports to_hash" > end > end > ... > end Or you could just do: duck[whatever].... and rescue the exception(s), possibly cascading down into a to_hash operation. You might as well fail without bothering with the respond_to? calls -- just ask the object to do what it's supposed to, and handle the error cases. David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)