liveBook · Manning

Sort!

As explained in The Well-Grounded Rubyist, Fourth Edition

sort! is a Ruby Array method that sorts the receiver in place.

sort! is a Ruby Array method that sorts the receiver in place. Sorting numbers is direct; sorting custom objects requires a comparison rule. section 10.8

The sorting behavior follows two paths:

  • Use each element’s <=> method when the objects define a natural ordering. section 10.8
  • Provide a block with two elements when the current operation needs another ordering or the elements lack <=>. section 10.8.1
  • Normalize unlike values inside the block when their default comparison is incompatible, such as converting strings and integers with to_i. section 10.8.1

Sorting objects by a chosen attribute

A Painting class can compare prices through <=>, while a block can override that ordering for a particular operation, such as sorting by year. The same comparison pattern applies when using sort! on an Array. section 10.8 section 10.8.1

Listing 10.3 Painting class implementing the spaceship operator
class Painting
  attr_reader :price
  def initialize(price)
    @price = price
  end
  def to_s
    "My price is #{price}."  1
  end
  def <=>(other_painting)
    self.price <=> other_painting.price  2
  end
end

This implementation shows how an object supplies the <=> comparison that an Array sorting operation can use. section 10.8

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains natural comparison, block-based overrides, and mixed-type normalization, but does not detail the sorting algorithm’s internals.
Examples
Uses integer arrays, Painting objects ordered by price or year, and arrays mixing numeric strings with integers.
What it assumes
Assumes familiarity with arrays and blocks while teaching how <=> enables custom objects to participate in sorting.
What you can do after
Apply it via Ruby Array methods with natural comparisons or a block-defined ordering.
How it connects
Connects Array sorting with Enumerable, the spaceship operator, blocks, and sort_by.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.