Closed
Description
The addition of the safe navigator operator appears to trigger this cop.
However, the fix can break the code.
Passes:
puts ([] || {}).length
Fails:
puts ([] || {})&.length
Expected behavior
Either leave it as it is:
puts ([] || {})&.length
or add extra parenthesis:
puts(([] || {})&.length)
Actual behavior
It removes the space:
puts([] || {})&.length
This can cause the code to return something different. In this example, when I put this line into a method it does not puts
anything, whereas before auto-correct it would print 0
to the console.
Steps to reproduce the problem
class Test
# rubocop does not mind this. Running the method will print `0`
def self.a
puts ([] || {}).length
end
# rubocop objects to this. Running the method will print `0`
def self.b
puts ([] || {})&.length
end
# rubocop autocorrects to this. Running the method will not print anything
def self.c
puts([] || {})&.length
end
# alternative fix that will print `0`
def self.d
puts(([] || {})&.length)
end
end
Use this code & run rubocop against it. You should find the behaviour matches the comments.
RuboCop version
1.30.1 (using Parser 3.1.2.0, rubocop-ast 1.18.0, running on ruby 2.6.6 -darwin21)
Activity