liveBook · Manning

Sort_by

As explained in The Well-Grounded Rubyist, Fourth Edition

sort_by is a Ruby Enumerable method that orders collection elements by comparing keys computed from each element by a block.

sort_by is an Enumerable method for ordering a collection by a key computed from each element. Give it one block argument, and Ruby uses the returned value to compare elements while preserving the original objects in the result. section 10.8.2

Normalize before sorting

["2", 1, 5, "3", 4, "6"].sort_by { |item| item.to_i } # => [1, "2", "3", 4, 5, "6"] The block converts every item to an integer for comparison, but the result still contains the original strings and integers. section 10.8.1

Unlike sort with a comparison block, sort_by does not require two block parameters or an explicit <=> call. It applies the same key computation to each element, then orders the collection by those keys. section 10.8.1 section 10.8.2

The method belongs to Enumerable, so it is available through enumerable containers such as arrays. Sorting custom objects can therefore use a derived attribute such as price without requiring those objects themselves to mix in Enumerable. section 10.8 section 10.8.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains key extraction and contrasts it with explicit comparison blocks, but defers deeper sorting-engine implementation.
Examples
Uses mixed strings and integers converted with to_i, alongside basic numeric arrays and custom objects sorted by attributes.
What it assumes
Assumes familiarity with blocks, collections, and basic comparison while demonstrating key normalization from mixed values.
What you can do after
Apply it via Ruby's Enumerable API to order objects by a computed attribute without writing pairwise comparison logic.
How it connects
Connects Enumerable, sort, comparison blocks, the spaceship operator, and Comparable.

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.