Today I Learned

hashrocket A Hashrocket project

Safe Navigation Operator

With the release of Ruby 2.3, the safe navigation operator (&.) is now available. This addition to the Ruby language allows you to collapse all those pesky nil checks into the accessor call they are guarding. Consider this snippet of common Ruby code:

if user && user.authenticate(params[:password])
  # proceed with logged in user
end

With the safe navigation operator, the predicate can now be collapsed:

if user&.authenticate(params[:password])
  # proceed with logged in user
end

If user is nil, then the predicate will evaluate to false and the body of the if-statement will be passed over.

Source

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.