From: David Alan Black Date: 2002-02-14T00:57:26+09:00 Subject: Re: qualms about respond_to? idiom Hi -- On Thu, 14 Feb 2002, Dave Thomas wrote: > David Alan Black writes: > > > I'm cool with Ruby's emphasis on object interface rather than type. > > The only thing is... I just can't get myself to be happy about this > > idiom: > > > > if obj.respond_to? "method" then obj.method end > > This is an interesting topic. Just to make sure we're talking about > the same thing, can I start with a question. > > When do you need to check the protocol of an object like this? One placed where I've used it (note that I'm skirting around the word "need" :-) is in NQXML::Dispatcher. There's a stream of events coming in. They are either start tags, text (i.e., element content), or end tags. If a tag comes along, I want to save it on the context stack if it's a start tag, and pop the stack if it's an end tag. 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. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav