Maybe Method for Ruby

Sometimes, when working in Ruby on Rails, I find myself writing code like:

foobar = FooBar.find(:first)
default = foobar.name if foobar

In Haskell, this would be a classic usage case for the Maybe monad. In Ruby, we don’t quite have the capabilities to make it implicit, but we can approximate the behavior explicitly:

class NilClass
  def maybe(*a); self; end
end
 
class Object
  alias :maybe :send
end
 
default = FooBar.find(:first).maybe(:name)

A small hack perhaps, but it saves a bit of typing.