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
str.match?(/ab/)
/ab/.match?(str)
str =~ /ab/
/ab/ =~ str
str.match(/ab/)
/ab/.match(str)
/ab/ === str

# good
str.include?('ab')

Constant Summary collapse

MSG =
'Use `%<negation>sString#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_csend, on_match_with_lvasgn

rubocop:disable Metrics/AbcSize



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/performance/string_include.rb', line 37

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

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

  add_offense(node, message: message) do |corrector|
    receiver, regex_str = regex_str, receiver if receiver.is_a?(String)
    regex_str = interpret_string_escapes(regex_str)
    dot = node.loc.dot ? node.loc.dot.source : '.'

    new_source = "#{'!' if negation}#{receiver.source}#{dot}include?(#{to_string_literal(regex_str)})"

    corrector.replace(node, new_source)
  end
end