class RuboCop::Cop::Performance::StartWith
/^ab/.match(‘abc’)
‘abc’.match(/^ab/)
/^ab/ =~ ‘abc’
‘abc’ =~ /^ab/
/^ab/.match?(‘abc’)
‘abc’.match?(/^ab/)
# bad
@example SafeMultiline: false
/^ab/.match(‘abc’)
‘abc’.match(/^ab/)
/^ab/ =~ ‘abc’
‘abc’ =~ /^ab/
/^ab/.match?(‘abc’)
‘abc’.match?(/^ab/)
# good
@example SafeMultiline: true (default)
‘abc’.start_with?(‘ab’)
# good
/Aab/.match(‘abc’)
‘abc’.match(/Aab/)
/Aab/ =~ ‘abc’
‘abc’ =~ /Aab/
/Aab/.match?(‘abc’)
‘abc’.match?(/Aab/)
# bad
@example
of the variables which rubocop doesn’t have.
object. Switching these methods has to be done with knowledge of the types
This will change to a new method call which isn’t guaranteed to be on the
@safety
for receiver is multiline string.
‘^start` is unsafe as it will behave incompatible with `start_with?`
This cop has `SafeMultiline` configuration option that `true` by default because
Identifies unnecessary use of a regex where `String#start_with?` would suffice.
def on_send(node)
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 = drop_start_metacharacter(regex_str) regex_str = interpret_string_escapes(regex_str) dot = node.loc.dot ? node.loc.dot.source : '.' new_source = "#{receiver.source}#{dot}start_with?(#{to_string_literal(regex_str)})" corrector.replace(node, new_source) end end