I have learnt that it’s called the safe navigation operator.
It returns nil if a method is called on nil.
[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 = 
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…
0 &.index(?a) # Will raise NoMethodError
Here’s a post from stackoverflow:
Hope this helps a bit…