Class: RuboCop::Cop::Performance::Sum

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

Overview

Identifies places where custom code finding the sum of elements in some Enumerable object can be replaced by ‘Enumerable#sum` method.

Examples:

OnlySumOrWithInitialValue: false (default)

# bad
[1, 2, 3].inject(:+)                        # Autocorrections for cases without initial value are unsafe
[1, 2, 3].inject(&:+)                       # and will only be performed when using the `-A` option.
[1, 2, 3].reduce { |acc, elem| acc + elem } # They can be prohibited completely using `SafeAutoCorrect: true`.
[1, 2, 3].reduce(10, :+)
[1, 2, 3].map { |elem| elem ** 2 }.sum
[1, 2, 3].collect(&:count).sum(10)

# good
[1, 2, 3].sum
[1, 2, 3].sum(10)
[1, 2, 3].sum { |elem| elem ** 2 }
[1, 2, 3].sum(10, &:count)

OnlySumOrWithInitialValue: true

# bad
[1, 2, 3].reduce(10, :+)
[1, 2, 3].map { |elem| elem ** 2 }.sum
[1, 2, 3].collect(&:count).sum(10)

# good
[1, 2, 3].sum(10)
[1, 2, 3].sum { |elem| elem ** 2 }
[1, 2, 3].sum(10, &:count)

Constant Summary collapse

MSG =
'Use `%<good_method>s` instead of `%<bad_method>s`.'
MSG_IF_NO_INIT_VALUE =
'Use `%<good_method>s` instead of `%<bad_method>s`, unless calling `%<bad_method>s` on an empty array.'
RESTRICT_ON_SEND =
%i[inject reduce sum].freeze

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/rubocop/cop/performance/sum.rb', line 115

def on_block(node)
  sum_with_block_candidate?(node) do |send, init, var_acc, var_elem, body|
    if acc_plus_elem?(body, var_acc, var_elem) || elem_plus_acc?(body, var_elem, var_acc)
      range = sum_block_range(send, node)
      message = build_block_message(send, init, var_acc, var_elem, body)

      add_offense(range, message: message) do |corrector|
        autocorrect(corrector, init, range)
      end
    end
  end
end

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



107
108
109
110
111
112
# File 'lib/rubocop/cop/performance/sum.rb', line 107

def on_send(node)
  return if empty_array_literal?(node)

  handle_sum_candidate(node)
  handle_sum_map_candidate(node)
end