Sha256: f92b78a90a19869562bbf574ccb9f8ff2a5f36338d277d58cded92e63337b318

Contents?: true

Size: 1.72 KB

Versions: 3

Compression:

Stored size: 1.72 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # This cop identifies use of `Regexp#match` or `String#match` in a context
      # where the integral return value of `=~` would do just as well.
      #
      # @example
      #   @bad
      #   do_something if str.match(/regex/)
      #   while regex.match('str')
      #     do_something
      #   end
      #
      #   @good
      #   method(str.match(/regex/))
      #   return regex.match('str')
      class RedundantMatch < Cop
        MSG = 'Use `=~` in places where the `MatchData` returned by ' \
              '`#match` will not be used.'.freeze

        # 'match' is a fairly generic name, so we don't flag it unless we see
        # a string or regexp literal on one side or the other
        def_node_matcher :match_call?, <<-END
          {(send {str regexp} :match _)
           (send !nil :match {str regexp})}
        END

        def_node_matcher :only_truthiness_matters?, <<-END
          ^({if while until case while_post until_post} equal?(%0) ...)
        END

        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, :expression)
        end

        def autocorrect(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) { corrector.replace(node.source_range, new_source) }
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rubocop-0.49.1 lib/rubocop/cop/performance/redundant_match.rb
rubocop-0.49.0 lib/rubocop/cop/performance/redundant_match.rb
rubocop-0.48.1 lib/rubocop/cop/performance/redundant_match.rb