Sami Sami - 1 year ago 164
Ruby Question

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

I came across this line of ruby code. What does

&.
mean in this?

@object&.method

Answer Source

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, similar to the try method in Rails.

So you can write

@spouse_name = @person&.spouse&.name

instead of

if(@person && @person.spouse)
  @spouse_name = @person.spouse.name
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download