Ruby中的`try`和`& .`(安全导航操作符)有什么区别? [英] What is the difference between `try` and `&.` (safe navigation operator) in Ruby
问题描述
这是我的代码:
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?
我觉得这不是红宝石相关的。葡萄可能吗?虽然我不知道它是怎么回事。
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相同,但如果出现NoMethodError异常,则会引发NoMethodError异常接收不是零,并没有实现尝试过的方法。
Same as #try, but will raise a NoMethodError exception if the receiving is not nil and does not implemented the tried method.
所以基本上它可以节省你在<$ c $上调用方法c> 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 Rails, or more accurately ActiveSupport. While safe navigation operator &.
is a language feature presented in Ruby 2.3.0.
这篇关于Ruby中的`try`和`& .`(安全导航操作符)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!