That nifty question mark

Posted 2006-12-16…

Here’s a pattern you see a lot of in Ruby:


foo.bar if foo.respond_to?(:bar)

I do this kind of thing frequently, as I’m a big fan of ducktyping over checking an object’s class explicitly. I’m not concerned with the class of an object as long as it does what I’m asking.

Io has a nice and simple way of doing this, built into the language:

  foo ?bar

If foo has slot bar (ie, in Rubyland it responds to bar), send the bar message to foo.

Simple trick: you can essentially bootstrap Ruby to do the same thing (note I use the word try in this example, which may have too much baggage for some of you):

class Object
  def try(meth, *args, &block)
    __send__(meth, *args, &block) if respond_to? meth
  end
end

Then you can do foo.try :bar

If the object doesn’t respond to the method, nil is returned, as in Io.