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

Style/SelectByRegexp flags/autocorrects hash.select incorrectly #10145

Closed
gsar opened this issue Sep 29, 2021 · 3 comments · Fixed by #10155
Closed

Style/SelectByRegexp flags/autocorrects hash.select incorrectly #10145

gsar opened this issue Sep 29, 2021 · 3 comments · Fixed by #10155
Assignees
Labels

Comments

@gsar
Copy link

gsar commented Sep 29, 2021

Expected behavior

I expect this cop to only apply to Array select and not to Hash select.

Actual behavior

Hash select is flagged if the arity is 1, even though the suggested autocorrect is wrong. i.e. hash.select {|k| /foo/.match? k } can't be replaced with hash.grep(/foo/), since single-arg grep always returns [] with hashes.

Steps to reproduce the problem

$ echo '{ a: 1, aa: 2 }.select { |k| /aa/.match? k }' | rubocop -sx -A
Inspecting 1 file
C

Offenses:

x:1:1: C: [Corrected] Style/SelectByRegexp: Prefer grep to select with a regexp match.
{ a: 1, aa: 2 }.select { |k| /aa/.match? k }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense corrected
====================
{ a: 1, aa: 2 }.grep(/aa/)

RuboCop version

1.22.0

@dvandersluis
Copy link
Member

Autocorrection by Style/SelectByRegexp is marked unsafe because, like with a bunch of other cops, RuboCop cannot know what type your hash variable is by static analysis, so it makes its best guess.

You could disable the cop for this line or use something like hash.keys.grep(/foo/).

@dvandersluis
Copy link
Member

That being said, if a literal hash is given, the cop should probably ignore it.

@dvandersluis dvandersluis self-assigned this Sep 29, 2021
@gsar
Copy link
Author

gsar commented Sep 29, 2021

@dvandersluis my actual code had stuff.to_hash.select ..., so i expect a hash literal or to_hash, to_h etc to be handled. thanks!

dvandersluis added a commit to dvandersluis/rubocop that referenced this issue Oct 1, 2021
…re the receiver appears to be a hash.
bbatsov pushed a commit that referenced this issue Oct 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
2 participants