Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 218
Roope Hakulinen Avatar asked Nov 16 '15 12:11

Roope Hakulinen


People also ask

What is safe navigation in Ruby?

Safe navigation operator¶ ↑ &. , called “safe navigation operator”, allows to skip method call when receiver is nil . It returns nil and doesn't evaluate method's arguments if the call is skipped.

What does safe navigation operator return?

Use the safe navigation operator ( ?. ) to replace explicit, sequential checks for null references. This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.

What is ||= in Ruby?

||= is called a conditional assignment operator. It basically works as = but with the exception that if a variable has already been assigned it will do nothing. First example: x ||= 10. Second example: x = 20 x ||= 10. In the first example x is now equal to 10.


1 Answers

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.

like image 182
Roope Hakulinen Avatar answered Oct 01 '22 20:10

Roope Hakulinen