Class: RuboCop::Cop::Performance::Sum
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Performance::Sum
- 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.
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
- #on_block(node) ⇒ Object
- #on_send(node) ⇒ Object (also: #on_csend)
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) = (send, init, var_acc, var_elem, body) add_offense(range, 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 |