Search code examples
ruby-on-railsruby

What does &. (ampersand dot) mean in Ruby?


I came across this line of ruby code. What does &. mean in this?

@object&.method

Solution

  • 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.