diff --git a/CHANGELOG.md b/CHANGELOG.md index 610ad42679..b5dadb9233 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -296,3 +296,4 @@ [@dvandersluis]: https://github.com/dvandersluis [@ghiculescu]: https://github.com/ghiculescu [@mfbmina]: https://github.com/mfbmina +[@mvz]: https://github.com/mvz diff --git a/changelog/fix_fix_error_in_performancesum_when_method.md b/changelog/fix_fix_error_in_performancesum_when_method.md new file mode 100644 index 0000000000..3b592c73d3 --- /dev/null +++ b/changelog/fix_fix_error_in_performancesum_when_method.md @@ -0,0 +1 @@ +* [#264](https://github.com/rubocop/rubocop/pull/264): Fix error in Performance/Sum when method has no brackets. ([@mvz][]) diff --git a/lib/rubocop/cop/performance/sum.rb b/lib/rubocop/cop/performance/sum.rb index df336773b3..30067a4c09 100644 --- a/lib/rubocop/cop/performance/sum.rb +++ b/lib/rubocop/cop/performance/sum.rb @@ -156,7 +156,7 @@ def autocorrect_sum_map(corrector, sum, map, init) end def sum_method_range(node) - range_between(node.loc.selector.begin_pos, node.loc.end.end_pos) + range_between(node.loc.selector.begin_pos, node.loc.expression.end_pos) end def sum_map_range(map, sum) diff --git a/spec/rubocop/cop/performance/sum_spec.rb b/spec/rubocop/cop/performance/sum_spec.rb index aa4aeb6824..a3267c543e 100644 --- a/spec/rubocop/cop/performance/sum_spec.rb +++ b/spec/rubocop/cop/performance/sum_spec.rb @@ -46,6 +46,17 @@ RUBY end + it "registers an offense and corrects when using `array.#{method} 0, :+`" do + expect_offense(<<~RUBY, method: method) + array.#{method} 0, :+ + ^{method}^^^^^^ Use `sum` instead of `#{method}(0, :+)`. + RUBY + + expect_correction(<<~RUBY) + array.sum + RUBY + end + it "registers an offense and corrects when using `array.#{method}(0.0, :+)`" do expect_offense(<<~RUBY, method: method) array.#{method}(0.0, :+) @@ -88,6 +99,15 @@ expect_no_corrections end + + it 'does not autocorrect `:+` without brackets when initial value is not provided' do + expect_offense(<<~RUBY, method: method) + array.#{method} :+ + ^{method}^^^ Use `sum` instead of `#{method}(:+)`, unless calling `#{method}(:+)` on an empty array. + RUBY + + expect_no_corrections + end end context 'when `SafeAutoCorrect: false' do @@ -114,6 +134,17 @@ array.sum RUBY end + + it 'autocorrects `:+` without brackets when initial value is not provided' do + expect_offense(<<~RUBY, method: method) + array.#{method} :+ + ^{method}^^^ Use `sum` instead of `#{method}(:+)`, unless calling `#{method}(:+)` on an empty array. + RUBY + + expect_correction(<<~RUBY) + array.sum + RUBY + end end it "registers an offense and corrects when using `array.#{method}(0, &:+)`" do