From: Robert Klemme Date: 2004-06-08T16:13:44+09:00 Subject: Method Checks (was: Re: How to ducktype a Hash?) First of all I'd like to make clear that this is still not Duck Typing! Duck Typing simply assumes the instance at hand is the one expected. If it's not the code may run anyway or you'll be bitten by a NoMethodError. "Sean O'Dell" schrieb im Newsbeitrag news:200406070944.10162.sean@celsoft.com... > I'm not sure what this means. I'm not looking for duck typing per se, just a > way to type check hash-like objects. The only two things I care about when > checking for something in this way are that the object responds to a group of > methods which all take the same number of parameter, and the group of methods > represent a described interface; that is, a known functionality. In this > particular case, the functionality should be that of a hash, or a hash-like > object. You can do it like this, although I still dislike the strong focus on type and type like checks: #!/usr/bin/ruby class MethodCriterium def initialize @methods = {} end def clear; @methods.clear; end def add(sym, arity) @methods[sym.to_sym] = arity self end def add_from_template(obj) obj.methods.each do |meth| add(meth, obj.method(meth).arity) end self end def satisfies(obj) begin @methods.each do |meth, arity| return false if arity != obj.method(meth).arity end true rescue NameError return false end end alias :=== :satisfies end a_hash = MethodCriterium.new a_hash.add(:[], 1).add(:[]=, 2) p a_hash === {} p a_hash === [] a_hash = MethodCriterium.new.add_from_template( {} ) p a_hash === {} p a_hash === [] an_array = MethodCriterium.new.add_from_template( [] ) [ [], {}, 5 ].each do |o| case o when a_hash puts "#{o.inspect} is a hash!" when an_array puts "#{o.inspect} is an array!" else puts "dunno bout #{o.inspect}" end end >>>> Use at own risk. <<<< Regards robert