-
-
Notifications
You must be signed in to change notification settings - Fork 88
Closed
Description
The ReverseEach performance cop suggests replacing .reverse.each with .reverse_each.
Unfortunately reverse_each is not a drop-in replacement for reverse.each as there is a subtle difference between the two:
payments = [200, 400, 800, 100]
max_payment = payments.sort.reverse.each { |x| "do something" }.last
# => 100
max_payment = payments.sort.reverse_each { |x| "do something" }.last
# => 800
In other words, reverse_each runs the block over each element in reverse order, as expected, but then it returns the un-reversed enumerable.
Solution
It's a valid performance improvement in most scenarios, but it needs to come with a big warning. I also think that auto-correction should be disabled for this cop because it can break code.
RuboCop version
rubocop -V
0.59.2 (using Parser 2.5.1.2, running on ruby 2.5.1 x86_64-linux)
Metadata
Metadata
Assignees
Labels
No labels