Skip to content

Commit

Permalink
Merge pull request #297 from r7kamura/feature/redundant-match
Browse files Browse the repository at this point in the history
Support autocorrection on `Performance/RedundantMatch` when receiver is a Regexp literal
  • Loading branch information
koic committed Jul 27, 2022
2 parents ae124b9 + 160998d commit c2bdc1a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
@@ -0,0 +1 @@
* [#297](https://github.com/rubocop/rubocop-performance/pull/297): Support autocorrection on `Performance/RedundantMatch` when receiver is a Regexp literal. ([@r7kamura][])
12 changes: 7 additions & 5 deletions lib/rubocop/cop/performance/redundant_match.rb
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/performance/redundant_match_spec.rb
Expand Up @@ -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

0 comments on commit c2bdc1a

Please sign in to comment.