class RuboCop::Cop::Performance::Detect
[].reverse.detect { |item| true }
[].detect { |item| true }
# good
[].filter { |item| true }[-1]
[].filter { |item| true }[0]
[].filter { |item| true }.last
[].filter { |item| true }.first
[].find_all { |item| true }.last
[].find_all { |item| true }.first
[].select { |item| true }.last
[].select { |item| true }.first
# bad
@example
if the receiver is a ‘Hash`, it may report a false positive.
`Array` or equivalent, but can’t reliably detect it. For example,
This cop is unsafe because it assumes that the receiver is an
@safety
`detect` instead.
chained to ‘select`, `find_all` or `filter` and change them to use
Identifies usages of `first`, `last`, `[0]` or `[-1]`
def accept_first_call?(receiver, body)
def accept_first_call?(receiver, body) caller, _first_method, args = *receiver # check that we have usual block or block pass return true if body.nil? && (args.nil? || !args.block_pass_type?) lazy?(caller) end
def autocorrect(corrector, node, replacement)
def autocorrect(corrector, node, replacement) receiver, _first_method = *node first_range = receiver.source_range.end.join(node.loc.selector) receiver, _args, _body = *receiver if receiver.block_type? corrector.remove(first_range) corrector.replace(receiver.loc.selector, replacement) end
def lazy?(node)
def lazy?(node) return false unless node receiver, method, _args = *node method == :lazy && !receiver.nil? end
def message_for_method(method, index)
def message_for_method(method, index) case method when :[] index == -1 ? INDEX_REVERSE_MSG : INDEX_MSG when :last REVERSE_MSG else MSG end end
def on_send(node)
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
def preferred_method
def preferred_method config.for_cop('Style/CollectionMethods')['PreferredMethods']['detect'] || 'detect' end
def register_offense(node, receiver, second_method, index)
def register_offense(node, receiver, second_method, index) _caller, first_method, _args = *receiver range = receiver.loc.selector.join(node.loc.selector) message = message_for_method(second_method, index) formatted_message = format(message, prefer: preferred_method, first_method: first_method, second_method: second_method, index: index) add_offense(range, message: formatted_message) do |corrector| autocorrect(corrector, node, replacement(second_method, index)) end end
def replacement(method, index)
def replacement(method, index) if method == :last || (method == :[] && index == -1) "reverse.#{preferred_method}" else preferred_method end end