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
[Fix #8327] Add new cop Style/SelectByRegexp
.
#10082
Conversation
I agree that the proposal results in more readable code. Might be a good idea to mention this in the style guide as well. I have to admit I keep forgetting about |
@marcandre requested this a long time ago and I came across it in my trek through the old issues 😁 I opened rubocop/ruby-style-guide#884. |
PR looks good 👍. Does it detect |
@marcandre do you mean |
Ah ah ah, yes, that's what I meant. It sows I'm doing a lot of elixir these days 😅 |
Also, should we consider enabling it for all versions of Ruby? It's a |
Up to @bbatsov but, despite being Style I think we shouldn't recommend something we know will be slower, and likely the average user would have no idea. It'd be cool if we could have the cop enabled or disabled by default based on target ruby version but then overridable... |
6493d43
to
8c903c9
Compare
I've updated this cop to be able to handle |
I think it's fine to suggest this on all supported Ruby versions with some disclaimer in the docs. It's OK for style cops to suggest something slower, but more readable. |
@dvandersluis Let's try to wrap this up this week, so we can include in the next RuboCop release. |
Gladly, but I need rubocop/rubocop-ast#209 to be released in order to do so. |
8c903c9
to
0b57dca
Compare
0b57dca
to
a2cd42b
Compare
@bbatsov rubocop-ast 1.12.0 was released, and this PR was updated to use it, and remove the target ruby version check. 🚀 |
Excellent! |
This cop suggests using
array.grep(regexp)
instead ofarray.select { |x| x.match?(regexp) }
andarray.grep_v(regexp)
instead ofarray.reject { |x| x.match?(regexp) }
on ruby >= 3.0. Previouslygrep
andgrep_v
were less performant so this is not recommended, but it was fixed in https://bugs.ruby-lang.org/issues/17030.I re-ran the benchmark from #8327 with some more possibilities:
select
vsgrep
benchmarkSince performance of
grep
is the same or better than all 4 options, they are all covered by this cop. I did not explicitly handle negative comparisons (ie.select { |x| x !~ REGEXP }
=>grep_v(REGEXP)
) asStyle/InverseMethods
can update it and then this cop will take over from there.I also benchmarked
reject
vsgrep_v
, and whilegrep_v
is on average slightly slower, I think it's still ok.reject
vsgrep_v
benchmarkFixes #8327.
Before submitting the PR make sure the following are checked:
[Fix #issue-number]
(if the related issue exists).master
(if not - rebase it).bundle exec rake default
. It executes all tests and runs RuboCop on its own code.{change_type}_{change_description}.md
if the new code introduces user-observable changes. See changelog entry format for details.