rubocop / rubocop-performance

An extension of RuboCop focused on code performance checks.
https://docs.rubocop.org/rubocop-performance
MIT License
670 stars 79 forks source link

Extend `Performance/Sum` to support method calls #455

Open toncid opened 2 months ago

toncid commented 2 months ago

Is your feature request related to a problem? Please describe.

Right now, Performance/Sum works well for numeric values, but it does not recognize method calls:

[1, 2, 3].inject(0) { |sum, e| sum + e }  # before
[1, 2, 3].sum  # after

[1, 2, 3].inject(0) { |sum, e| sum + e.to_i }  # no suggestion

No-op calls of to_i are here just to paint the picture. 🙂

Describe the solution you'd like

It would be nice if RuboCop could recognize and simplify expressions as follows:

[1, 2, 3].inject(0) { |sum, e| sum + e.to_i }  # before
[1, 2, 3].sum(&:to_i)  # after

Describe alternatives you've considered

I have checked RuboCop Rails and enabled ActiveSupportExtensionsEnabled, but this case does not seem to be supported by them.

Additional context

It might even be a safe operation. I am not aware of any downsides to it.