123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Performance::SortReverse

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, AutoCorrector, Base
Instance Chain:
self, ::RuboCop::Cop::SortBlock, RangeHelp, Base
Inherits: Base
  • Object
Defined in: lib/rubocop/cop/performance/sort_reverse.rb

Overview

Identifies places where sort { |a, b| b <⇒ a } can be replaced by a faster sort.reverse.

Examples:

# bad
array.sort { |a, b| b <=> a }

# good
array.sort.reverse

Constant Summary

Instance Method Summary

Instance Method Details

#on_block(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/sort_reverse.rb', line 22

def on_block(node)
  sort_with_block?(node) do |send, var_a, var_b, body|
    replaceable_body?(body, var_b, var_a) do
      register_offense(send, node)
    end
  end
end

#on_numblock(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/sort_reverse.rb', line 30

def on_numblock(node)
  sort_with_numblock?(node) do |send, arg_count, body|
    next unless arg_count == 2

    replaceable_body?(body, :_2, :_1) do
      register_offense(send, node)
    end
  end
end

#register_offense(send, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/sort_reverse.rb', line 42

def register_offense(send, node)
  range = sort_range(send, node)
  prefer = "sort#{send.loc.dot.source}reverse"

  message = format(MSG, prefer: prefer)

  add_offense(range, message: message) do |corrector|
    corrector.replace(range, prefer)
  end
end