Method_missing, politely

In their Polite Programmer talk at Rubyconf, Jim Weirich and Chris Nelson pointed out that merely adding some behavior with method_missing wasn't quite polite, as shown below:


In order for respond_to? to return true, one can specialize it, as follows:


This is better, but it still doesn't make play_some_Beethoven behave exactly like a method. Indeed:


Ruby 1.9.2 introduces respond_to_missing? that provides for a clean solution to the problem. Instead of specializing respond_to? one specializes respond_to_missing?. Here's a full example:

2 comments:

Priit said...

Thanks for writeup, didn't know about respond_to_missing method, nice indeed :-)

Found small code typo, it should be "Here's some #{$1}".

shevy said...

cool

this should get widespread more

I didn't know about it until someone posted the link on IRC just now

Post a Comment