Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#519](https://github.com/rubocop/rubocop-performance/issues/519): Fix false positives for `Performance/StringInclude` when a method is called on the result of `match`. ([@kshtzkr][])
14 changes: 13 additions & 1 deletion lib/rubocop/cop/performance/string_include.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ class StringInclude < Base
# rubocop:disable-next Metrics/AbcSize
def on_send(node)
return unless (receiver, regex_str = redundant_regex?(node))
return if match_result_used?(node)

negation = node.send_type? && node.method?(:!~)
negation = negation?(node)
message = format(MSG, negation: ('!' if negation))

add_offense(node, message: message) do |corrector|
Expand All @@ -55,6 +56,17 @@ def on_send(node)

private

# `match` returns `MatchData`, so a call on its result is not a predicate.
def match_result_used?(node)
return false unless node.call_type? && node.method?(:match)

node.parent&.call_type? && node.parent.receiver == node
end

def negation?(node)
node.send_type? && node.method?(:!~)
end

def literal?(regex_str)
regex_str.match?(/\A#{Util::LITERAL_REGEX}+\z/o)
end
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/performance/string_include_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,14 @@
expect_no_offenses('expect(subject.spin).to match(/\A\n/)')
end

it 'does not register an offense when a method is called on the result of `match`' do
expect_no_offenses(<<~RUBY)
str.match(/abc/).to_s
str.match(/abc/)&.to_s
/abc/.match(str)[0]
RUBY
end

it 'registers an offense and corrects when argument of `match?` is not a string literal' do
expect_offense(<<~RUBY)
/ /.match?(content)
Expand Down