Class: RuboCop::Cop::Performance::RegexpMatch

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

Overview

In Ruby 2.4, ‘String#match?`, `Regexp#match?`, and `Symbol#match?` have been added. The methods are faster than `match`. Because the methods avoid creating a `MatchData` object or saving backref. So, when `MatchData` is not used, use `match?` instead of `match`.

Examples:

# bad
def foo
  if x =~ /re/
    do_something
  end
end

# bad
def foo
  if x !~ /re/
    do_something
  end
end

# bad
def foo
  if x.match(/re/)
    do_something
  end
end

# bad
def foo
  if /re/ === x
    do_something
  end
end

# good
def foo
  if x.match?(/re/)
    do_something
  end
end

# good
def foo
  if !x.match?(/re/)
    do_something
  end
end

# good
def foo
  if x =~ /re/
    do_something(Regexp.last_match)
  end
end

# good
def foo
  if x.match(/re/)
    do_something($~)
  end
end

# good
def foo
  if /re/ === x
    do_something($~)
  end
end

Constant Summary collapse

TYPES_IMPLEMENTING_MATCH =

Constants are included in this list because it is unlikely that someone will store ‘nil` as a constant and then use it for comparison

%i[const regexp str sym].freeze
MSG =
'Use `match?` instead of `%<current>s` when `MatchData` is not used.'
MATCH_NODE_PATTERN =
<<~PATTERN
  {
    #match_method?
    #match_with_int_arg_method?
    #match_operator?
    #match_threequals?
    #match_with_lvasgn?
  }
PATTERN

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.autocorrect_incompatible_withObject



134
135
136
# File 'lib/rubocop/cop/performance/regexp_match.rb', line 134

def self.autocorrect_incompatible_with
  [ConstantRegexp]
end

Instance Method Details

#match_with_lvasgn?(node) ⇒ Boolean

Returns:

  • (Boolean)


105
106
107
108
109
110
# File 'lib/rubocop/cop/performance/regexp_match.rb', line 105

def match_with_lvasgn?(node)
  return false unless node.match_with_lvasgn_type?

  regexp, _rhs = *node
  regexp.to_regexp.named_captures.empty?
end

#on_case(node) ⇒ Object



142
143
144
145
146
147
148
149
150
# File 'lib/rubocop/cop/performance/regexp_match.rb', line 142

def on_case(node)
  return if node.condition

  node.each_when do |when_node|
    when_node.each_condition do |condition|
      check_condition(condition)
    end
  end
end

#on_if(node) ⇒ Object



138
139
140
# File 'lib/rubocop/cop/performance/regexp_match.rb', line 138

def on_if(node)
  check_condition(node.condition)
end