问题描述
Ruby 2.3.0引入了安全导航语法,该语法通过引入一个仅在前一个语句的值不是 nil .这是一个功能,例如在C#,Groovy和Swift中已经存在.例如,在Groovy中 ,语法是
foo?.bar
这基本上意味着结果值是 foo.bar 的值,除非 foo 为 null ,在这种情况下,返回值也是 null ,因此不会引发异常.也 C#(称为空条件运算符 )和 Swift (称为 optional-chaining表达式)使用此表示法.
因此,其他语言的语法似乎很标准.现在,为什么在Ruby中语法是
foo&.bar
相反?
此答案基于 the Ruby问题跟踪中有关功能请求的讨论.根据 Ruby的作者Yukihiro Matsumoto ,不可能引入运算符Ruby中的?.
,因为foo?
是有效的方法名称,因此无法解析.运算符的第一个候选者是反向序列.?
.该语法已已实现(由中田伸吉),但后来被丢弃为它被认为与其他语言引入的原始语法过于接近(如前所述,这是不可行的).最终语法&.
被松本(Matsumoto)接受为建议. >
这是松本给出的这种语法的理由
此语法随后作为 Ruby 2.3.0-preview1 .
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?
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
This syntax was then released as part of Ruby 2.3.0-preview1.
这篇关于为什么Ruby为安全的导航运算符使用其自己的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!