Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #165] Fix a false positive for Performance/Sum #166

Merged
merged 1 commit into from
Sep 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Bug fixes

* [#164](https://github.com/rubocop-hq/rubocop-performance/pull/164): Fix an error for `Performance/CollectionLiteralInLoop` when a method from `Enumerable` is called with no receiver. ([@eugeneius][])
* [#165](https://github.com/rubocop-hq/rubocop-performance/issues/165): Fix a false positive for `Performance/Sum` when using initial value argument is a variable. ([@koic][])

## 1.8.0 (2020-09-04)

Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/performance/sum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def build_good_method(init)

unless init.empty?
init = init.first
good_method += "(#{init.source})" if init.source.to_i != 0
good_method += "(#{init.source})" unless init.int_type? && init.value.zero?
end
good_method
end
Expand Down
33 changes: 33 additions & 0 deletions spec/rubocop/cop/performance/sum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,39 @@
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, :+)
^{method}^^^^^^^^^ Use `sum(0.0)` instead of `#{method}(0.0, :+)`.
RUBY

expect_correction(<<~RUBY)
array.sum(0.0)
RUBY
end

it "registers an offense and corrects when using `array.#{method}(init, :+)`" do
expect_offense(<<~RUBY, method: method)
array.#{method}(init, :+)
^{method}^^^^^^^^^^ Use `sum(init)` instead of `#{method}(init, :+)`.
RUBY

expect_correction(<<~RUBY)
array.sum(init)
RUBY
end

it 'does not autocorrect when initial value is not provided' do
expect_offense(<<~RUBY, method: method)
array.#{method}(:+)
Expand Down