做什么 &.(和号)在 Ruby 中是什么意思?

做什么 &.(和号)在 Ruby 中是什么意思?

问题描述:

我遇到了这行 ruby​​ 代码.&. 在这里是什么意思?

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_object.my_method

这会将 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 不会被调用当接收者为 nil 时,结果为 nil.在这种情况下,不评估 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.