Class: RuboCop::Cop::Performance::StringInclude

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/performance/string_include.rb

Overview

Identifies unnecessary use of a regex where `String#include?` would suffice.

Examples:

# bad
'abc'.match?(/ab/)
/ab/.match?('abc')
'abc' =~ /ab/
/ab/ =~ 'abc'
'abc'.match(/ab/)
/ab/.match('abc')

# good
'abc'.include?('ab')

Constant Summary collapse

MSG =
'Use `String#include?` instead of a regex match with literal-only pattern.'
RESTRICT_ON_SEND =
%i[match =~ match?].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_match_with_lvasgn



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/performance/string_include.rb', line 34

def on_send(node)
  return unless (receiver, regex_str = redundant_regex?(node))

  add_offense(node) do |corrector|
    receiver, regex_str = regex_str, receiver if receiver.is_a?(String)
    regex_str = interpret_string_escapes(regex_str)

    new_source = "#{receiver.source}.include?(#{to_string_literal(regex_str)})"

    corrector.replace(node.source_range, new_source)
  end
end