On Thu, Jan 20, 2011 at 11:56 PM, Charles Oliver Nutter <headius / headius.com
> wrote:

> On Thu, Jan 20, 2011 at 7:01 PM, Jim Weirich <jim.weirich / gmail.com>
> wrote:
> >
> > On Jan 20, 2011, at 7:52 PM, Charles Oliver Nutter wrote:
> >
> >> This also short-circuits further calls...but it's pretty ugly :)
> >
> > Also doesn't work if a method returns a type other than self.class.
>
> Well, you'd mix this into Object or something if you wanted it globally...
>

Really, this is a deeper question of programming philosophy. The problem
isn't the lack of a ?., &., #try, etc. method. The problem is that nil does
not respond to arbitrary messages in Ruby. Contrast this with Objective-C,
where NIL responds to arbitrary messages with NIL.

You can quite easily replicate Objective-C behavior in Ruby with the
following:

irb(main):001:0> def maybe_a_string
irb(main):002:1>   ["test", nil][rand(2)]
irb(main):003:1> end
=> nil
irb(main):004:0> maybe_a_string.slice(1,2)
=> "es"
irb(main):005:0> maybe_a_string.slice(1,2)
NoMethodError: undefined method `slice' for nil:NilClass
from (irb):5
from :0
irb(main):006:0> class<<nil
irb(main):007:1>   def method_missing(meth, *args)
irb(main):008:2>     nil
irb(main):009:2>   end
irb(main):010:1> end
=> nil
irb(main):011:0> maybe_a_string.slice(1,2)
=> "es"
irb(main):012:0> maybe_a_string.slice(1,2)
=> nil