Ruby 2.3.0 introduces the safe navigation syntax that eases the nil handling of chained method calls by introducing a new operator that only calls the method if val
This answer is based on the discussion of the feature request in Ruby's issue tracking. According to Ruby's author Yukihiro Matsumoto it wouldn't be possible to introduce operator ?.
in Ruby because foo?
is valid method name and thus it couldn't be parsed. The first candidate for operator was reversed sequence .?
. That syntax was already implemented (by Nobuyoshi Nakada) but was later discarded as it was thought to be too close to original syntax introduced by the other languages (that was not feasible as mentioned earlier). The final syntax &.
was accepted as suggested by Matsumoto.
Here's the justification for this syntax given by Matsumoto
I think about this for a while, and thinking of introducing
&.
instead of.?
, because:
.?
is similar to?.
in Swift and other languages, but is different anyway.- Since
?
is a valid suffix of method names in Ruby, we already see a lot of question marks in our programs.u&.profile
reminds us as short form ofu && u.profile
.But behavior of
&.
should be kept, i.e. it should skipnil
but recognizefalse
.
This syntax was then released as part of Ruby 2.3.0-preview1.