class RuboCop::Cop::Performance::StringInclude

This cop identifies unnecessary use of a regex where `String#include?` would suffice.

This cop's offenses are not safe to auto-correct if a receiver is nil.

@example

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

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

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_match_with_lvasgn(node)
Alias for: on_send
on_send(node) click to toggle source
# 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
Also aliased as: on_match_with_lvasgn

Private Instance Methods

literal?(regex_str) click to toggle source
# File lib/rubocop/cop/performance/string_include.rb, line 50
def literal?(regex_str)
  regex_str.match?(/\A#{Util::LITERAL_REGEX}+\z/o)
end