123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Performance::StartWith

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, AutoCorrector, Base
Instance Chain:
Inherits: Base
  • Object
Defined in: lib/rubocop/cop/performance/start_with.rb

Overview

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

This cop has SafeMultiline configuration option that true by default because ^start is unsafe as it will behave incompatible with start_with? for receiver is multiline string.

Examples:

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

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

SafeMultiline: true (default)

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

SafeMultiline: false

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

Cop Safety Information:

  • This will change to a new method call which isn’t guaranteed to be on the object. Switching these methods has to be done with knowledge of the types of the variables which rubocop doesn’t have.

Constant Summary

Instance Attribute Summary

Instance Method Summary

Instance Method Details

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/start_with.rb', line 77

alias on_csend on_send

#on_match_with_lvasgn(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/start_with.rb', line 78

alias on_match_with_lvasgn on_send

#on_send(node) Also known as: #on_csend, #on_match_with_lvasgn

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/start_with.rb', line 63

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