class RuboCop::Cop::Performance::RedundantMatch

This cop 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.

@example

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

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

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/performance/redundant_match.rb, line 38
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)
  end
end

Private Instance Methods

autocorrect(corrector, node) click to toggle source
# File lib/rubocop/cop/performance/redundant_match.rb, line 50
def autocorrect(corrector, node)
  # Regexp#match can take a second argument, but this cop doesn't
  # register an offense in that case
  return unless node.first_argument.regexp_type?

  new_source = "#{node.receiver.source} =~ #{node.first_argument.source}"

  corrector.replace(node.source_range, new_source)
end