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

后端 未结 1 1748
无人共我
无人共我 2021-01-17 21:28

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

相关标签:
1条回答
  • 2021-01-17 21:35

    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.

    0 讨论(0)
提交回复
热议问题