Bocchi operator (&.)

I tried to write an article about the bocchi operator (&.) I learned in the reference book of Ruby on rails 5 quick learning practice guide that can be used in the field as a record of study.

What is the Bocchi operator (&.)?

Calling a method with the operator &. will eliminate the error even if the receiver is nil.

class User
  def name
    'name'
  end
end
> user = User.new
> user.name
=> 'name'


#①
> object = nil
> object&.name
=> nil

#②
> object.name
Traceback (most recent call last):
...
NoMethodError (undefined method `name' for nil:NilClass)

In (2), if the object that is the receiver is nil, an error will occur without using the bocchi operator. In ①, nil is returned by using the bocchi operator and no error occurs.

reference

・ Ruby on rails 5 that can be used in the field

Recommended Posts

Bocchi operator (&.)
Self-assignment operator
Reference ternary operator
Increment operator, decrement operator
Control syntax operator