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

Cop idea: replace list = list.select {...} with list.select! {...} #432

Open
vlad-pisanov opened this issue Jan 10, 2024 · 2 comments
Open

Comments

@vlad-pisanov
Copy link
Contributor

When the result of select, reject, uniq, sort, sort_by, map, flatten, and reverse is assigned back to the variable it operates on, prefer the mutable version of the method, i.e.

# bad
list = list.select(&:odd?)
list = list.reject { |x| x > 42 }
list = list.uniq
list = list.sort
list = list.sort_by(&:name)

# good
list.select!(&:odd?)
list.reject! { |x| x > 42 }
list.uniq!
list.sort!
list.sort_by!(&:name)

This could also be a performance cop since mutating in-place can have performance advantages.

@koic
Copy link
Member

koic commented Jan 10, 2024

Yeah, this is likely similar to the Performance/ChainArrayAllocation cop, so I will transfer it to rubocop-performance.

@koic koic transferred this issue from rubocop/rubocop Jan 10, 2024
@amomchilov
Copy link

This could substantially reduce allocations/copies, but it's quite a can of worms.

The transformation is equivalent only if list isn't shared. This is hard enough in a statically-typed language with good lifetime analysis, but even harder in a dynamic language like Ruby.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants