From: "David A. Black" Date: 2007-10-23T04:02:24+09:00 Subject: Re: Conflicts between using respond_to? and extending Ruby Hi -- On Tue, 23 Oct 2007, ara.t.howard wrote: > > On Oct 22, 2007, at 11:26 AM, David A. Black wrote: > >> >>> case obj >>> when Array >>> ... >>> >>> is safer and more accurate. i think it really depends on the use case - i >>> personally use both. >> >> It does indeed depend; they do totally different things. > > not entirely - they both allowing pre-testing to see if code is going to work > or explode... Pre-testing is what you do, not what the method does :-) >> I was >> describing the differences, specifically in the context of duck typing >> (or alternatives to duck typing): respond_to? gives you information >> about an object at a given moment, and kind_of? tells you about its >> ancestry. > > well sortof: > > OpenStruct.new.respond_to?(:foo) #=> false > > OpenStruct.new.foo() #=> nil You're a hard task-master :-) OK, I'll try again: respond_to?(:x) gives you information about an object at a given moment -- namely, whether or not any of the classes or modules currently in an object's method lookup-path has a method "x" defined (including the object's singleton class). kind_of?(m) tells you about an object's ancestry -- namely, whether or not a class or module called m is among its ancestral classes and modules. And yes, I know you can do: s = "hi" def s.respond_to?(x) true end and I think people have sometimes even advocated this for OpenStructs. But the above is as watertight as I can get :-) > as i said, i think it's 100% situational and you really can't make blanket > rules. I think we're talking at cross purposes; I wasn't suggesting rules, blanket or otherwise, just commenting on the difference(s) between respond_to? and kind_of? David -- Upcoming training by David A. Black/Ruby Power and Light, LLC: * Advancing with Rails, Edison, NJ, November 6-9 * Advancing with Rails, Berlin, Germany, November 19-22 * Intro to Rails, London, UK, December 3-6 (by Skills Matter) See http://www.rubypal.com for details!