On Wed, Jan 19, 2011 at 6:27 PM, Rodrigo Rosenfeld Rosas
<rr.rosas / gmail.com> wrote:
> One of the few things I like in Groovy that Ruby doesn't support is the '?.'
> operator. For instance:
>
> obj?.somePropertyName?.anotherGreatPropertyName?.anotherOne

I'm not opposed to the feature, but it does tend to cause nils to
propagate through the system even more. Devs become lazy about
checking return values and end up just using ?. everywhere. Suddenly
an API that can't deal with a nil gets a nil, and you have no idea
where it came from because you've got all these chains of ?. calls.

This is the justification given for *not* adding the feature in the
set of small Java language changes recently. A number of other
features got in, but this one was very contentious, because people
were worried about all those nulls going around. In the Java case,
there was the additional problem of how to treat a ?. call that's
supposed to return a primitive number...and that case is largely
irreconcilable.

In Ruby, I don't think it's as bad as in Java. There is the syntax
question, to be sure.

There's also the possibility that existing libraries do this fine.
Here's another:

module SafeCall
  def _(&block)
    if self == nil || block == nil
      return self
    else
      return self.instance_eval &block
    end
  end
end

class NilClass
  include SafeCall
end

class Foo
  include SafeCall
  def a
    self
  end

  def b
    nil
  end

  def c
    self
  end
end

puts Foo.new._{a._{b._{c}}}
puts Foo.new._{a._{c}}

This also short-circuits further calls...but it's pretty ugly :)

- Charlie