为什么Ruby为安全的导航运算符使用其自己的语法? [英] Why does Ruby use its own syntax for safe navigation operator?

查看:95
本文介绍了为什么Ruby为安全的导航运算符使用其自己的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 2.3.0引入了安全导航语法,该语法通过引入一个仅在前一个语句的值不是 nil .这是一个功能,例如在C#,Groovy和Swift中已经存在.例如,在Groovy中 ,语法是

foo?.bar

这基本上意味着结果值是 foo.bar 的值,除非 foo null ,在这种情况下,返回值也是 null ,因此不会引发异常.也 C#(称为空条件运算符 )和解决方案

此答案基于 the Ruby问题跟踪中有关功能请求的讨论.根据 Ruby的作者Yukihiro Matsumoto ,不可能引入运算符Ruby中的?.,因为foo?是有效的方法名称,因此无法解析.运算符的第一个候选者是反向序列.?.该语法已已实现(由中田伸吉),但后来被丢弃为它被认为与其他语言引入的原始语法过于接近(如前所述,这是不可行的).最终语法&.被松本(Matsumoto)接受为建议. >

这是松本给出的这种语法的理由

我考虑了一段时间,并考虑引入&.而不是.?,因为:

  • .?与Swift和其他语言中的?.相似,但是仍然有所不同.
  • 由于?是Ruby中方法名称的有效后缀,因此我们已经在程序中看到很多问号.
  • u&.profile提醒我们u && u.profile的缩写形式.

但是应保留&.的行为,即应跳过nil但可以识别false.

此语法随后作为 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

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.

这篇关于为什么Ruby为安全的导航运算符使用其自己的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆