From: James Edward Gray II Date: 2007-03-02T07:30:37+09:00 Subject: Re: Duck Typing Hash-Like Objects On Mar 1, 2007, at 4:25 PM, Gary Wright wrote: > I often find that when writing initialize (or alternate constructors) > I want to examine the class of the arguments to decide how to > proceed. An example is Array.new, which behaves differently if it > is given an integer argument or an array argument: > > Array.new 2 # [nil,nil] > Array.new [1,2] # [1,2] > > These sorts of tests can be done via Class#=== or Kernel#is_a? or > Kernel#kind_of? but that can lead to artificial constraints. Using > Kernel#respond_to? seems to avoid many of those constraints. > > 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? I would check for to_hash(), then call that method on the argument to get its Hash representation. James Edward Gray II