diff --git a/changelog/fix_incorrect_autocorrect_for_ambiguous_operator.md b/changelog/fix_incorrect_autocorrect_for_ambiguous_operator.md new file mode 100644 index 00000000000..f1142eb4fac --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_ambiguous_operator.md @@ -0,0 +1 @@ +* [#9671](https://github.com/rubocop/rubocop/pull/9671): Fix an incorrect auto-correct for `Lint/AmbiguousOperator` with `Style/MethodCallWithArgsParentheses`. ([@koic][]) diff --git a/lib/rubocop/cop/util.rb b/lib/rubocop/cop/util.rb index 7dc59c90513..6916c8da532 100644 --- a/lib/rubocop/cop/util.rb +++ b/lib/rubocop/cop/util.rb @@ -38,7 +38,10 @@ def add_parentheses(node, corrector) elsif node.arguments.empty? corrector.insert_after(node, '()') else - corrector.replace(args_begin(node), '(') + args_begin = args_begin(node) + + corrector.remove(args_begin) + corrector.insert_before(args_begin, '(') corrector.insert_after(args_end(node), ')') end end diff --git a/spec/rubocop/cli/autocorrect_spec.rb b/spec/rubocop/cli/autocorrect_spec.rb index 4b66eb090ee..5aa956e18f0 100644 --- a/spec/rubocop/cli/autocorrect_spec.rb +++ b/spec/rubocop/cli/autocorrect_spec.rb @@ -236,6 +236,29 @@ def batch RUBY end + it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with ' \ + '`Lint/AmbiguousOperator`' do + create_file('.rubocop.yml', <<~YAML) + Style/MethodCallWithArgsParentheses: + EnforcedStyle: require_parentheses + YAML + create_file('example.rb', <<~RUBY) + def foo(&block) + do_something &block + end + RUBY + expect( + cli.run( + ['--auto-correct', '--only', 'Style/MethodCallWithArgsParentheses,Lint/AmbiguousOperator'] + ) + ).to eq(0) + expect(IO.read('example.rb')).to eq(<<~RUBY) + def foo(&block) + do_something(&block) + end + RUBY + end + it 'corrects `Style/IfUnlessModifier` with `Style/SoleNestedConditional`' do source = <<~RUBY def foo