Note. Although @Santosh gave a clear and complete answer, I would like to add some more background and add an important note regarding its use with non-instance variables.
It is called “ Safe Navigator” (“Optional Chain Operator”, “Operator with Zero Condition”, etc.). Matz seems to call this a “lone operator.” This was introduced in Ruby 2.3 . It sends a method to an object only if it is not nil .
Example:
"Edge case" with local variables:
Please note that the above code uses instance variables. If you want to use a safe navigation operator with local variables, you will need to first verify that the local variables are defined.
# `user` local variable is not defined previous user&.profile # This code would throw the following error: NameError: undefined local variable or method `user' for main:Object
To fix this problem, check if your local variable is defined, or set it to nil:
# Option 1: Check the variable is defined if defined?(user) user&.profile end # Option 2: Define your local variable. Example, set it to nil user = nil user&.profile # Works and does not throw any errors
Method Background
Rails has a try method that basically does the same thing. It uses the send method to call the method. Matz suggested that it is slow, and this should be a built-in language feature.
Many other programming languages have a similar feature: Objective-C, Swift, Python, Scala, CoffeeScript, etc. However, the general syntax is ?. (question dot). But this syntax was not accepted by Ruby. Since ? allowed in method names and therefore character sequence ?. is already valid Ruby code. For example:
2.even?.class
That's why the Ruby community had to come up with a different syntax. It was an active discussion, and various options were considered ( .? , ? , && , etc.). Here is a list of some considerations:
u.?profile.?thumbnails u\profile\thumbnails u!profile!thumbnails u ? .profile ? .thumbnails u && .profile && .thumbnails # And finally u&.profile&.thumbnails
When choosing syntax, the developers looked at different boundary cases, and the discussion is quite useful for going through. If you want to see all the options and nuances of the operator, see the discussion of this function on the official tracker buffer for Ruby.