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.
So you can write
@person&.spouse&.name
instead of
@person.spouse.name if @person && @person.spouse
From the Docs:
my_object.my_method
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
.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…