Class: RuboCop::Cop::Performance::RedundantMatch

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/performance/redundant_match.rb

Overview

Identifies the use of ‘Regexp#match` or `String#match`, which returns `#<MatchData>`/`nil`. The return value of `=~` is an integral index/`nil` and is more performant.

Examples:

# bad
do_something if str.match(/regex/)
while regex.match('str')
  do_something
end

# good
method(str =~ /regex/)
return value unless regex =~ 'str'

Constant Summary collapse

MSG =
'Use `=~` in places where the `MatchData` returned by `#match` will not be used.'
RESTRICT_ON_SEND =
%i[match].freeze
HIGHER_PRECEDENCE_OPERATOR_METHODS =
%i[| ^ & + - * / % ** > >= < <= << >>].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/performance/redundant_match.rb', line 39

def on_send(node)
  return unless match_call?(node) &&
                (!node.value_used? || only_truthiness_matters?(node)) &&
                !(node.parent && node.parent.block_type?)

  add_offense(node) do |corrector|
    autocorrect(corrector, node) if autocorrectable?(node)
  end
end