From: David Alan Black Date: 2002-02-14T20:15:22+09:00 Subject: Re: qualms about respond_to? idiom Hi -- On Thu, 14 Feb 2002, Avi Bryant wrote: > > All tags respond to tagStart? and tagEnd? But not all events in my > > stream are tags. So.... > > > > if e.respond_to? :tagStart? > > context.push(e.name) if e.tagStart? > > end > > > > is my way of testing, first, whether it's a tag (but without actually > > checking whether it's a tag), and, second, whether it's a start tag. > > This is a case where I wish I knew a way to avoid the duplication, > > which feels really clunky to me. > > Ok, how about: > > class Object > def try_sending(msg, *args) > if respond_to? msg > yield send(msg, *args) > end > end > end > > e.try_sending(:tagStart?) {|s| context.push(e.name) if s} I certainly like the general idea of something that does this in one step, though I think it would be hard to handle iterators (since you've already got a block). Also, it doesn't let you branch on non-finding of the method. That's perhaps an insurmountable problem with combining these steps (and not using exceptions): how do you flag that a method wasn't found, as opposed to finding a method that returns false or nil? David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav