diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c8d009bb9c..0651bfd46c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ * [#8807](https://github.com/rubocop-hq/rubocop/pull/8807): Fix a false positive for `Style/RedundantCondition` when using assignment by hash key access. ([@koic][]) * [#8848](https://github.com/rubocop-hq/rubocop/issues/8848): Fix a false positive for `Style/CombinableLoops` when using the same method with different arguments. ([@dvandersluis][]) * [#8843](https://github.com/rubocop-hq/rubocop/issues/8843): Fix an incorrect autocorrect for `Lint/AmbiguousRegexpLiteral` when sending method to regexp literal receiver. ([@koic][]) +* [#8835](https://github.com/rubocop-hq/rubocop/issues/8835): Fix an incorrect autocorrect for `Style/RedundantInterpolation` when using string interpolation for non-operator methods. ([@koic][]) ### Changes diff --git a/lib/rubocop/cop/style/redundant_interpolation.rb b/lib/rubocop/cop/style/redundant_interpolation.rb index 9ade739712f..dec1e339a25 100644 --- a/lib/rubocop/cop/style/redundant_interpolation.rb +++ b/lib/rubocop/cop/style/redundant_interpolation.rb @@ -51,7 +51,12 @@ def single_interpolation?(node) end def single_variable_interpolation?(node) - node.children.one? && variable_interpolation?(node.children.first) + return false unless node.children.one? + + first_child = node.children.first + + variable_interpolation?(first_child) || + first_child.send_type? && !first_child.operator_method? end def interpolation?(node) diff --git a/spec/rubocop/cop/style/redundant_interpolation_spec.rb b/spec/rubocop/cop/style/redundant_interpolation_spec.rb index ca63c5cbe51..cc9ac4d7d6c 100644 --- a/spec/rubocop/cop/style/redundant_interpolation_spec.rb +++ b/spec/rubocop/cop/style/redundant_interpolation_spec.rb @@ -157,6 +157,28 @@ RUBY end + it 'registers an offense for "#{number}"' do + expect_offense(<<~'RUBY') + "#{number}" + ^^^^^^^^^^^ Prefer `to_s` over string interpolation. + RUBY + + expect_correction(<<~'RUBY') + number.to_s + RUBY + end + + it 'registers an offense for "#{do_something(42)}"' do + expect_offense(<<~'RUBY') + "#{do_something(42)}" + ^^^^^^^^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation. + RUBY + + expect_correction(<<~'RUBY') + do_something(42).to_s + RUBY + end + it 'registers an offense for "#{var}"' do expect_offense(<<~'RUBY') var = 1; "#{var}"