class RuboCop::Cop::Performance::SortReverse
array.sort.reverse
# good
array.sort { |a, b| b <=> a }
# bad
@example
can be replaced by a faster ‘sort.reverse`.
Identifies places where `sort { |a, b| b <=> a }`
def on_block(node)
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
def on_numblock(node)
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
def register_offense(send, node)
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