From: Jeff 'japhy' Pinyan Date: 2002-02-14T01:14:36+09:00 Subject: Re: qualms about respond_to? idiom On Feb 13, Dave Thomas said: >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? I believe the functionality was borrowed from Perl's universal object method, "can". Perl code: if ($object->can($method_name)) { $object->$method_name(@args); } # you can also store the return value of can() into a scalar # which holds the function reference and call it instead of # doing a dynamic method call: # $object->$code_ref(@args) which is like the Ruby code: if object.responds_to?("foo") then object.foo(...) end As to *WHY* it's needed, it's there primarily because in Perl, classes can inherit from multiple other classes, and dynamically, too. And if you have to choose one of a set of classes, some of which are more capable than others (this might be reaching...) it's nice to be able to say: my $object = AnyMailer->new(); if ($code = $object->can("PGP")) { $object->$code($my_pgp_stuff); } # etc. It's also good for dispatch tables. -- Jeff "japhy" Pinyan japhy@pobox.com http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ ** Look for "Regular Expressions in Perl" published by Manning, in 2002 ** what does y/// stand for? why, yansliterate of course. [ I'm looking for programming work. If you like my work, let me know. ]