Lint/ParenthesesAsGroupedExpression with a space and a `&` auto-corrects to invalid code · Issue #10719 · rubocop/rubocop · GitHub
Skip to content

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

Closed
@reedstonefood

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions