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.
I have learnt that it’s called the safe navigation operator.
It returns nil if a method is called on nil.
For example:
[we will back to the array part later on]
100 &.class # => Integer
1 &.next # => 2
2 &.+(5) # => 7
a = 'hello' # => "hello"
# The object id's don't change
p a.equal?(a &.itself) # => true
# You are just calling the methods on `a`
# But what if a becomes nil for some reason:
a = nil # => nil
a &.next # => nil
# You see this program didn't just crash!
# We didn't run the next method on nil!
The a becoming nil can be due to various reasons. One is that when you run STDIN.gets on IDE like Atom + Atom Runner / VS Code + Code Runner, STDIN#gets returns nil because the runner can’t accept inputs!
The example on your code is another reason.
# Say you expect a nested array a to contain other array elements. But it's empty
a = []
a.first.length if a.first # => nil
a.first &.length # => nil
If you did:
a = []
a.first.length
You would raise the NoMethodError because you are calling a.first, which returns nil, then the length method on nil, which is really not present…
So you avoided a if statement and saved your code from a crash…
So basically the &.something makes your code a bit safer depending on what you are doing!
Do note that if the method after &.meth doesn’t exist, and the object is not nil, it will raise NoMethodError as normal…