diff --git a/changelog/change_support_autocorrection_on_redundantmatch.md b/changelog/change_support_autocorrection_on_redundantmatch.md new file mode 100644 index 0000000000..fb22405e51 --- /dev/null +++ b/changelog/change_support_autocorrection_on_redundantmatch.md @@ -0,0 +1 @@ +* [#297](https://github.com/rubocop/rubocop-performance/pull/297): Support autocorrection on `Performance/RedundantMatch` when receiver is a Regexp literal. ([@r7kamura][]) diff --git a/lib/rubocop/cop/performance/redundant_match.rb b/lib/rubocop/cop/performance/redundant_match.rb index c2fa42c0c4..e4754fecc7 100644 --- a/lib/rubocop/cop/performance/redundant_match.rb +++ b/lib/rubocop/cop/performance/redundant_match.rb @@ -41,21 +41,23 @@ def on_send(node) !(node.parent && node.parent.block_type?) add_offense(node) do |corrector| - autocorrect(corrector, node) + autocorrect(corrector, node) if autocorrectable?(node) end end private def autocorrect(corrector, node) - # Regexp#match can take a second argument, but this cop doesn't - # register an offense in that case - return unless node.first_argument.regexp_type? - new_source = "#{node.receiver.source} =~ #{node.first_argument.source}" corrector.replace(node.source_range, new_source) end + + def autocorrectable?(node) + # Regexp#match can take a second argument, but this cop doesn't + # register an offense in that case + node.receiver.regexp_type? || node.first_argument.regexp_type? + end end end end diff --git a/spec/rubocop/cop/performance/redundant_match_spec.rb b/spec/rubocop/cop/performance/redundant_match_spec.rb index 72e4548504..a72dc4710b 100644 --- a/spec/rubocop/cop/performance/redundant_match_spec.rb +++ b/spec/rubocop/cop/performance/redundant_match_spec.rb @@ -111,4 +111,15 @@ def method(str) ^^^^^^^^^^^^^^^^^^ Use `=~` in places where the `MatchData` returned by `#match` will not be used. RUBY end + + it 'registers an offense and corrects when receiver is a Regexp literal' do + expect_offense(<<~RUBY) + something if /regex/.match(str) + ^^^^^^^^^^^^^^^^^^ Use `=~` in places where the `MatchData` returned by `#match` will not be used. + RUBY + + expect_correction(<<~RUBY) + something if /regex/ =~ str + RUBY + end end