问题描述
我碰到了这一行红宝石代码. &.
这是什么意思?
I came across this line of ruby code. What does &.
mean in this?
@object&.method
推荐答案
它称为安全导航操作员.它在Ruby 2.3.0中引入,它使您可以调用对象上的方法而不必担心对象可能是nil
(避免出现undefined method for nil:NilClass
错误),类似于 Rails中的try
方法.
It is called the Safe Navigation Operator. Introduced in Ruby 2.3.0, it lets you call methods on objects without worrying that the object may be nil
(Avoiding an undefined method for nil:NilClass
error), similar to the try
method in Rails.
所以你可以写
@person&.spouse&.name
代替
@person.spouse.name if @person && @person.spouse
从文档:
这会将my_method消息发送到my_object.任何 对象可以是接收者,但取决于方法的可见性 发送消息可能会引发NoMethodError.
This sends the my_method message to my_object. Any object can be a receiver but depending on the method's visibility sending a message may raise a NoMethodError.
您可以使用&.指定接收者,则不调用my_method 当接收者为零时,结果为零.在这种情况下, 不评估my_method的参数.
You may use &. to designate a receiver, then my_method is not invoked and the result is nil when the receiver is nil. In that case, the arguments of my_method are not evaluated.
这篇关于是什么. (和号)在Ruby中表示什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!