I came across this line of ruby code. What does &.
mean in this?
@object&.method
ベストアンサー1
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 tomy_object
. Any object can be a receiver but depending on the method's visibility sending a message may raise aNoMethodError
.You may use
&.
to designate a receiver, thenmy_method
is not invoked and the result isnil
when the receiver isnil
. In that case, the arguments ofmy_method
are not evaluated.