diff --git a/CHANGELOG.md b/CHANGELOG.md index 42a5c979cd..09aab6e2a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#207](https://github.com/rubocop-hq/rubocop-performance/issues/207): Fix an error for `Performance/Sum` when using `map(&do_something).sum` without receiver. ([@koic][]) + ## 1.9.2 (2021-01-01) ### Bug fixes diff --git a/lib/rubocop/cop/performance/sum.rb b/lib/rubocop/cop/performance/sum.rb index 211b17425c..df336773b3 100644 --- a/lib/rubocop/cop/performance/sum.rb +++ b/lib/rubocop/cop/performance/sum.rb @@ -150,7 +150,9 @@ def autocorrect_sum_map(corrector, sum, map, init) replacement = build_good_method(init, block_pass) corrector.remove(sum_range) - corrector.replace(map_range, ".#{replacement}") + + dot = '.' if map.receiver + corrector.replace(map_range, "#{dot}#{replacement}") end def sum_method_range(node) @@ -228,7 +230,11 @@ def build_block_bad_method(method, init, var_acc, var_elem, body) end def method_call_with_args_range(node) - node.receiver.source_range.end.join(node.source_range.end) + if (receiver = node.receiver) + receiver.source_range.end.join(node.source_range.end) + else + node.source_range + end end end end diff --git a/spec/rubocop/cop/performance/sum_spec.rb b/spec/rubocop/cop/performance/sum_spec.rb index cc4c5b978b..c9c2eb5817 100644 --- a/spec/rubocop/cop/performance/sum_spec.rb +++ b/spec/rubocop/cop/performance/sum_spec.rb @@ -190,6 +190,17 @@ RUBY end + it "registers an offense and corrects when using `#{method}(&:count).sum`" do + expect_offense(<<~RUBY, method: method) + %{method}(&:count).sum + ^{method}^^^^^^^^^^^^^ Use `sum { ... }` instead of `%{method} { ... }.sum`. + RUBY + + expect_correction(<<~RUBY) + sum(&:count) + RUBY + end + it "registers an offense and corrects when using `array.#{method}(&:count).sum(10)`" do expect_offense(<<~RUBY, method: method) array.%{method}(&:count).sum(10)