为什么 Ruby 对安全导航运算符使用自己的语法?
Why does Ruby use its own syntax for safe navigation operator?
Ruby 2.3.0 引入了安全导航语法,它通过引入一个新运算符来简化对链式方法调用的 nil 处理,该运算符仅在前面的语句不是 nil。这是一个已经存在的特性,例如在 C#、Groovy 和 Swift 中。例如in Groovy,语法为
foo?.bar
这基本上意味着结果值是 foo.bar 除非 foo 是 null,在这种情况下,return 值也是 null,因此不会抛出异常。 C# (called null-conditional operators) and Swift(称为可选链接表达式)也使用此表示法。
所以语法在其他语言中似乎很标准。现在,为什么 Ruby 的语法是
foo&.bar
而不是?
此答案基于 Matsumoto 的 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。
这是 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
.
此语法随后作为 Ruby 2.3.0-preview1 的一部分发布。
Ruby 2.3.0 引入了安全导航语法,它通过引入一个新运算符来简化对链式方法调用的 nil 处理,该运算符仅在前面的语句不是 nil。这是一个已经存在的特性,例如在 C#、Groovy 和 Swift 中。例如in Groovy,语法为
foo?.bar
这基本上意味着结果值是 foo.bar 除非 foo 是 null,在这种情况下,return 值也是 null,因此不会抛出异常。 C# (called null-conditional operators) and Swift(称为可选链接表达式)也使用此表示法。
所以语法在其他语言中似乎很标准。现在,为什么 Ruby 的语法是
foo&.bar
而不是?
此答案基于 Matsumoto 的 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。
这是 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
.
此语法随后作为 Ruby 2.3.0-preview1 的一部分发布。