Ruby 中的“try"和“&."(安全导航操作符)有什么区别 [英] What is the difference between `try` and `&.` (safe navigation operator) in Ruby

查看:22
本文介绍了Ruby 中的“try"和“&."(安全导航操作符)有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

class Order < Grape::Entity
  expose :id { |order, options| order.id.obfuscate }
  expose :time_left_to_review do |order, options|
    byebug
    order&.time_left_to_review # ERROR
  end
  expose :created_at { |order, options| order.last_transition.created_at }
end

# NoMethodError Exception: undefined method `time_left_to_review' for #<Order:0x007f83b9efc970>

我认为 &..try 的快捷方式,但我想我错了.有人可以指出我缺少的东西的正确方向吗?

I thought &. is a shortcut for .try but I guess I was wrong. May someone point me to the right direction regarding what I am missing?

我觉得这与 ruby​​ 无关.也许是葡萄?虽然我不明白这是怎么回事.

I feel like it's not ruby related. Grape maybe? Though I don't get how it could be.

推荐答案

&. 的工作原理类似于 #try!,而不是 #try.

&. works like #try!, not #try.

这里是 #try! 的描述(来自 文档):

And here is description of #try! (from documentation):

与#try 相同,但如果接收不是 nil 并且没有实现所尝试的方法,则会引发 NoMethodError 异常.

Same as #try, but will raise a NoMethodError exception if the receiving is not nil and does not implemented the tried method.

所以基本上它可以让您免于在 nil 上调用方法,但是如果呈现一个对象,它会像往常一样尝试调用它的方法.

So basically it saves you from calling a method on nil, but if an object is presented it will try to call its method as usual.

引自 Rails 文档,所以强调这一点很重要Ruby 不提供 #try;它由 Rails 提供,或者更准确地说是 ActiveSupport.安全导航运算符(&.) 但是,是 Ruby 2.3.0 中提供的语言特性.

The quote is from Rails Documentation, and so it's important to emphasize that Ruby does not provide #try; it's provided by Rails, or more accurately ActiveSupport. The safe navigation operator (&.) however, is a language feature presented in Ruby 2.3.0.

这篇关于Ruby 中的“try"和“&amp;."(安全导航操作符)有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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