class RuboCop::Cop::Performance::StringInclude
str.include?(‘ab’)
# good
/ab/ === str
/ab/.match(str)
str.match(/ab/)
/ab/ =~ str
str =~ /ab/
/ab/.match?(str)
str.match?(/ab/)
# bad
@example
This cop’s offenses are not safe to autocorrect if a receiver is nil or a Symbol.
@safety
Identifies unnecessary use of a regex where ‘String#include?` would suffice.
def literal?(regex_str)
def literal?(regex_str) regex_str.match?(/\A#{Util::LITERAL_REGEX}+\z/o) end
def on_send(node)
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