diff --git a/changelog/fix_incorrect_autocorrect_for_lint_number_conversion.md b/changelog/fix_incorrect_autocorrect_for_lint_number_conversion.md new file mode 100644 index 00000000000..5f04d30c28a --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_lint_number_conversion.md @@ -0,0 +1 @@ +* [#9633](https://github.com/rubocop/rubocop/pull/9633): Fix an incorrect auto-correct for `Lint/NumberConversion` when `to_i` method in symbol form. ([@koic][]) diff --git a/lib/rubocop/cop/lint/number_conversion.rb b/lib/rubocop/cop/lint/number_conversion.rb index 0e8f0bdeff0..9ae49cb7c7d 100644 --- a/lib/rubocop/cop/lint/number_conversion.rb +++ b/lib/rubocop/cop/lint/number_conversion.rb @@ -105,6 +105,8 @@ def handle_as_symbol(node) corrected_method: correct_sym_method(to_method) ) add_offense(node, message: message) do |corrector| + remove_parentheses(corrector, node) if node.parenthesized? + corrector.replace(sym_node, correct_sym_method(to_method)) end end @@ -120,6 +122,11 @@ def correct_sym_method(to_method) "{ |i| #{body} }" end + def remove_parentheses(corrector, node) + corrector.replace(node.loc.begin, ' ') + corrector.remove(node.loc.end) + end + def ignore_receiver?(receiver) if receiver.send_type? && ignored_method?(receiver.method_name) true diff --git a/spec/rubocop/cop/lint/number_conversion_spec.rb b/spec/rubocop/cop/lint/number_conversion_spec.rb index 950fc16f471..e628c4074e4 100644 --- a/spec/rubocop/cop/lint/number_conversion_spec.rb +++ b/spec/rubocop/cop/lint/number_conversion_spec.rb @@ -131,7 +131,18 @@ RUBY expect_correction(<<~RUBY) - "1,2,3,foo,5,6,7,8".split(',').map({ |i| Integer(i, 10) }) + "1,2,3,foo,5,6,7,8".split(',').map { |i| Integer(i, 10) } + RUBY + end + + it 'registers offense and autocorrects without parentheses' do + expect_offense(<<~RUBY) + "1,2,3,foo,5,6,7,8".split(',').map &:to_i + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using &:to_i, use stricter { |i| Integer(i, 10) }. + RUBY + + expect_correction(<<~RUBY) + "1,2,3,foo,5,6,7,8".split(',').map { |i| Integer(i, 10) } RUBY end @@ -142,7 +153,7 @@ RUBY expect_correction(<<~RUBY) - "foo".try({ |i| Float(i) }) + "foo".try { |i| Float(i) } RUBY end @@ -153,7 +164,7 @@ RUBY expect_correction(<<~RUBY) - "foo".send({ |i| Complex(i) }) + "foo".send { |i| Complex(i) } RUBY end end