diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bf6d801908..154b618ac53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/rubocop/cop/style/redundant_sort.rb b/lib/rubocop/cop/style/redundant_sort.rb index 4621bb53da8..a610c7b0e5b 100644 --- a/lib/rubocop/cop/style/redundant_sort.rb +++ b/lib/rubocop/cop/style/redundant_sort.rb @@ -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)} ) } diff --git a/spec/rubocop/cop/style/redundant_sort_spec.rb b/spec/rubocop/cop/style/redundant_sort_spec.rb index 424cd5654cb..a8f0d0d5f0d 100644 --- a/spec/rubocop/cop/style/redundant_sort_spec.rb +++ b/spec/rubocop/cop/style/redundant_sort_spec.rb @@ -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