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

Support Ruby 2.7's numbered parameter for Style/RedundantSort #7783

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,7 @@
### New features

* [#7654](https://github.com/rubocop-hq/rubocop/issues/7654): Support `with_fixed_indentation` option for `Layout/ArrayAlignment` cop. ([@nikitasakov][])
* [#7783](https://github.com/rubocop-hq/rubocop/pull/7783): Support Ruby 2.7's numbered parameter for `Style/RedundantSort`. ([@koic][])

### Bug fixes

Expand Down
4 changes: 2 additions & 2 deletions lib/rubocop/cop/style/redundant_sort.rb
Expand Up @@ -63,9 +63,9 @@ class RedundantSort < Cop
(send $(send _ $:sort_by _) ${:last :first})
(send $(send _ $:sort_by _) ${:[] :at :slice} {(int 0) (int -1)})

(send (block $(send _ ${:sort_by :sort}) ...) ${:last :first})
(send ({block numblock} $(send _ ${:sort_by :sort}) ...) ${:last :first})
(send
(block $(send _ ${:sort_by :sort}) ...)
({block numblock} $(send _ ${:sort_by :sort}) ...)
${:[] :at :slice} {(int 0) (int -1)}
)
}
Expand Down
38 changes: 38 additions & 0 deletions spec/rubocop/cop/style/redundant_sort_spec.rb
Expand Up @@ -178,4 +178,42 @@
expect(new_source).to eq('foo.max_by { |x| x.something }')
end
end

context '>= Ruby 2.7', :ruby27 do
context 'when using numbered parameter' do
it 'registers an offense and corrects when last is called on sort with ' \
'comparator' do
expect_offense(<<~RUBY)
foo.sort { _2 <=> _1 }.last
^^^^^^^^^^^^^^^^^^^^^^^ Use `max` instead of `sort...last`.
RUBY

expect_correction(<<~RUBY)
foo.max { _2 <=> _1 }
RUBY
end

it 'registers an offense and corrects when first is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2, 3].sort_by { _1.length }.first
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
RUBY

expect_correction(<<~RUBY)
[1, 2, 3].min_by { _1.length }
RUBY
end

it 'registers an offense and corrects when at(0) is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2, 3].sort_by { _1.foo }.at(0)
^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...at(0)`.
RUBY

expect_correction(<<~RUBY)
[1, 2, 3].min_by { _1.foo }
RUBY
end
end
end
end