Search code examples
rubysyntaxlanguage-designsafe-navigation-operator

Why does Ruby use its own syntax for safe navigation operator?


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 value of previous statement is not nil. This is a feature that already exists for example in C#, Groovy and Swift. For example in Groovy, the syntax is

foo?.bar

which basically means that the result value is that of foo.bar unless foo is null, in which case the return value is also null and thus no exception is thrown. Also C# (called null-conditional operators) and Swift (called optional-chaining expression) use this notation.

So the syntax seems to be quite standard in other languages. Now, why in Ruby the syntax is

foo&.bar

instead?


Solution

  • 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 of u && u.profile.

    But behavior of &. should be kept, i.e. it should skip nil but recognize false.

    This syntax was then released as part of Ruby 2.3.0-preview1.