Class: RuboCop::Cop::Gusto::MinByMaxBy

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

Overview

Checks for the use of ‘min` or `max` with a proc. Corrects to `min_by` or `max_by`.

Examples:

# bad
arr = [[3, 3, 3], [2, 2], [1]]
arr.min(&:count)
 => [3, 3, 3] - oh no how did this happen?
arr = [[2,2],[1,1],[3,3,3]]
arr.min &:first # => TypeError: no implicit conversion of Array into Integer
arr = [[1, 1], [3, 3], [2, 2]]
arr.max { |pair| pair.first } # => [2, 2] (semantically incorrect)

# good
arr = [[2,2],[1],[3,3,3]]
arr.min_by &:first # => [1]
arr = [[1, 1], [3, 3], [2, 2]]
arr.max_by { |pair| pair.first } # => [3, 3]

Constant Summary collapse

MSG =
"Use `%{method}_by` instead of `%{method}` with a proc like `&:my_method_proc`. `%{method}` expects Comparable elements."
RESTRICT_ON_SEND =
%i(min max).freeze

Instance Method Summary collapse

Instance Method Details

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



32
33
34
35
36
37
38
39
40
# File 'lib/rubocop/cop/gusto/min_by_max_by.rb', line 32

def on_send(node)
  return unless node.arguments?
  return unless node.first_argument.block_pass_type?

  method_name = node.method_name
  add_offense(node, message: format(MSG, method: method_name)) do |corrector|
    corrector.replace(node, node.source.sub(method_name.to_s, "#{method_name}_by"))
  end
end