Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lint/ParenthesesAsGroupedExpression with a space and a & auto-corrects to invalid code #10719

Closed
reedstonefood opened this issue Jun 17, 2022 · 0 comments · Fixed by #10720
Closed
Labels

Comments

@reedstonefood
Copy link

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)
koic added a commit to koic/rubocop that referenced this issue Jun 17, 2022
…edExpression`

Fixes rubocop#10719 and follow up rubocop#8039.

This PR fixes a false positive for `Lint/ParenthesesAsGroupedExpression`
when using safe navigation operator.
@koic koic added the bug label Jun 17, 2022
koic added a commit that referenced this issue Jun 17, 2022
…entheses_as_grouped_expression

[Fix #10719] Fix a false positive for `Lint/ParenthesesAsGroupedExpression`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants