On 3/1/07, Gary Wright <gwtmp01 / mac.com> 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

This requires the keys method though, which thinking back, I usually
don't provide in my hash-like classes. So I don't know...

Jacob Fugal