Objective-C message passing semantics for Ruby
Tuesday, April 15, 2008 at 5:11PM object.respond_to?(method) ? object.send(method, args) : nil
that is, if a particular object implements a method then please call it and let me know what it returns, otherwise just pretend I never asked and return `nil`. While mulling over the `git diff`, it occurred to me that is (if I remember correctly) exactly how Objective-C behaves by default with message passing.
And so could Ruby:
Kernel.module_eval do
def method_missing(*args, &block)
nil
end
end
I am in no way advocating this as not being insane (a number of projects rely on the existing default `method_missing` implementation which raises an exception), but it is possible. :-)
Let's see it in action in irb. Before:
irb(main):001:0> o = Object.new
=> #
irb(main):002:0> o.method_that_does_not_exist
NoMethodError: undefined method `method_that_does_not_exist' for #
from /Users/mathie/.irbrc:210:in `method_missing'
from (irb):2
And after:
irb(main):008:0> o = Object.new
=> #
irb(main):009:0> o.method_that_does_not_exist
=> nil
Could be useful if Objective-C is your hammer and you find yourself trying to use Ruby as a hammer instead?
Reader Comments (4)
This reminds me a lot of a post I made about the ? operator in Io -- remarkably similar issue; http://codefluency.com/articles/2006/12/16/that-nifty-question-mark
This is just stupid. Good luck searching bugs with this code.
Instead of going ape-crazy and making it affect all method calls, why not just go:
This way, every object you now have can be asked to do something gingerly:
You wont affect pre-existing methods and modules, but you still get delicious convenience. Or even:
And then:
This way, you won't pollute method missing for everyone, and you can do regular calls without having to do symbols, like so:
And so forth. By all means, Ruby is an expressive wonderland of pleasure, but just with other expressive wonderlands of pleasure, you want to use protection so you don't make a mess.
Just to be clear; I wasn't advocating actually doing this, just noting that it was possible. :-) If you actually want semantics like this, then @Leon's comment is a sane way to get it. The key thing it does is that it makes it explicit to the reader of the code that you're wanting those semantics. My insane version will trip up any other programmer that touches your application!