Skip to content

Performance/ReverseEach fix is not equivalent #36

@cyclotron3k

Description

@cyclotron3k

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions