Class: RuboCop::Cop::Performance::Detect

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

Overview

Identifies usages of ‘first`, `last`, `[0]` or `[-1]` chained to `select`, `find_all` or `filter` and change them to use `detect` instead.

Examples:

# bad
[].select { |item| true }.first
[].select { |item| true }.last
[].find_all { |item| true }.first
[].find_all { |item| true }.last
[].filter { |item| true }.first
[].filter { |item| true }.last
[].filter { |item| true }[0]
[].filter { |item| true }[-1]

# good
[].detect { |item| true }
[].reverse.detect { |item| true }

Constant Summary collapse

CANDIDATE_METHODS =
Set[:select, :find_all, :filter].freeze
MSG =
'Use `%<prefer>s` instead of `%<first_method>s.%<second_method>s`.'
REVERSE_MSG =
'Use `reverse.%<prefer>s` instead of `%<first_method>s.%<second_method>s`.'
INDEX_MSG =
'Use `%<prefer>s` instead of `%<first_method>s[%<index>i]`.'
INDEX_REVERSE_MSG =
'Use `reverse.%<prefer>s` instead of `%<first_method>s[%<index>i]`.'
RESTRICT_ON_SEND =
i[first last []].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rubocop/cop/performance/detect.rb', line 50

def on_send(node)
  detect_candidate?(node) do |receiver, second_method, args|
    if second_method == :[]
      index = args
      args = {}
    end

    return unless args.empty?
    return unless receiver

    receiver, _args, body = *receiver if receiver.block_type?
    return if accept_first_call?(receiver, body)

    register_offense(node, receiver, second_method, index)
  end
end