gpt4 book ai didi

ruby - 为什么 Ruby 使用自己的安全导航运算符语法?

转载 作者:数据小太阳 更新时间:2023-10-29 06:52:37 24 4
gpt4 key购买 nike

Ruby 2.3.0 引入了安全导航语法,它通过引入一个新的运算符来简化链式方法调用的 nil 处理,该运算符仅在先前语句的值不是 nil< 时才调用该方法/em>。这是一个已经存在于 C#、Groovy 和 Swift 中的特性。例如in Groovy , 语法是

foo?.bar

这基本上意味着结果值是 foo.bar 除非 foonull,在这种情况下返回值也是null 因此不会抛出异常。还有 C# (称为空条件运算符)和Swift (称为可选链接表达式)使用此表示法。

所以语法在其他语言中似乎是相当标准的。现在,为什么在 Ruby 中语法是

foo&.bar

代替?

最佳答案

此答案基于 the discussion of the feature request在 Ruby 的问题跟踪中。根据Ruby's author Yukihiro Matsumoto在 Ruby 中不可能引入运算符 ?. 因为 foo? 是有效的方法名称,因此无法解析。第一个候选运算符是反向序列 .?。该语法是 already implemented (由 Nobuyoshi Nakada 编写)但后来被丢弃,因为它被认为太接近其他语言引入的原始语法(如前所述,这是不可行的)。最终语法 &. 被接受为 suggested作者:松本。

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

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 - 为什么 Ruby 使用自己的安全导航运算符语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33735228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com