123456789_123456789_123456789_123456789_123456789_

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

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, AutoCorrector, Base
Instance Chain:
self, Base
Inherits: Base
  • Object
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

Instance Method Summary

Instance Method Details

#autocorrect(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_match.rb', line 51

def autocorrect(corrector, node)
  new_source = "#{node.receiver.source} =~ #{replacement(node)}"

  corrector.replace(node, new_source)
end

#autocorrectable?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_match.rb', line 57

def autocorrectable?(node)
  # Regexp#match can take a second argument, but this cop doesn't
  # register an offense in that case
  node.receiver.regexp_type? || node.first_argument.regexp_type?
end

#call_like?(arg) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_match.rb', line 86

def call_like?(arg)
  arg.call_type? || arg.yield_type? || arg.super_type?
end

#on_send(node)

[ GitHub ]

  
# 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

#replacement(node) (private)

[ GitHub ]

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

def replacement(node)
  arg = node.first_argument

  if requires_parentheses?(arg)
    "(#{arg.source})"
  else
    arg.source
  end
end

#requires_parentheses?(arg) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_match.rb', line 73

def requires_parentheses?(arg)
  return true if arg.if_type? && arg.ternary?
  return true if arg.operator_keyword? || arg.range_type?

  call_like?(arg) && requires_parentheses_for_call_like?(arg)
end

#requires_parentheses_for_call_like?(arg) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/redundant_match.rb', line 80

def requires_parentheses_for_call_like?(arg)
  return false if arg.parenthesized? || !arg.arguments?

  !HIGHER_PRECEDENCE_OPERATOR_METHODS.include?(arg.method_name)
end