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

How to detect when the result of Array#sort isn't captured? #7446

Closed
cstyles opened this issue Oct 18, 2019 · 2 comments · Fixed by #7448
Closed

How to detect when the result of Array#sort isn't captured? #7446

cstyles opened this issue Oct 18, 2019 · 2 comments · Fixed by #7448

Comments

@cstyles
Copy link
Contributor

cstyles commented Oct 18, 2019

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

Apologies if this already exists but I couldn't find anything by searching. Is there a way to report when the result of something like Array#sort or Hash#merge isn't captured?

Describe the solution you'd like

I'd like to see a cop that will detect when these types of methods are called but their return value isn't stored in a variable, passed as an argument, or used in some other way. In that case, I would like it if rubocop would suggest Array#sort! or Hash#merge! to do the operation in-place.

edit: It occurred to me after the fact that it's not always apparent that we're calling sort or merge on an Array or Hash and we wouldn't necessarily want to suggest sort! for other (possibly user-defined) classes where sort might have side effects. So I don't think this is easy to implement, at least not for a dynamically typed language like Ruby.

@buehmann
Copy link
Contributor

I haven't tried this, but it looks as if https://docs.rubocop.org/en/stable/cops_lint/#lintvoid could do the trick.

@cstyles
Copy link
Contributor Author

cstyles commented Oct 19, 2019

Oh wow, that's exactly what I wanted!

It looks like the list of methods that it checks for doesn't include merge. I just opened a PR to add it. Thanks for your help!

bbatsov pushed a commit that referenced this issue Oct 21, 2019
Fixes #7446

Now, if `merge` is used in a void context, the `Lint/Void` cop will
register an offense and the mutating `merge!` method will be suggested.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants