做什么 &.(和号)在 Ruby 中是什么意思? [英] What does &. (ampersand dot) mean in Ruby?

查看:29
本文介绍了做什么 &.(和号)在 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.

这篇关于做什么 &.(和号)在 Ruby 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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