RUBY / CHAPTER 08

Sorting and deterministic tie rules

Intermediate

Order results without mutating inputs or leaving ties unexplained.

By the end of this chapter

  • Use sort_by for compound keys
  • Preserve originals when required
  • Distinguish sorted search from arbitrary search

The idea

Sorting needs a clear ordering rule, especially when several records share the same primary value. sort_by can compute a compound key such as [score, name], making secondary ordering explicit. A nonbang sorting method returns a new outer array, while sort! changes the receiver. Neither operation automatically duplicates mutable objects stored inside that array.

A report should not depend on unspecified tie behavior when consistent ordering matters. Include a stable identifier or original index as a secondary key if the requirement needs it. Searching can also depend on ordering: a binary-search predicate must change monotonically across the input. For an unsorted collection, a linear find is appropriate unless the program first establishes and maintains the required sorted order.

Ruby example
records=[{score:2,name:"B"},{score:1,name:"C"},{score:2,name:"A"}]
ordered=records.sort_by { |r| [r[:score],r[:name]] }
puts ordered.map { |r| r[:name] }.join(",")
Result
C,A,B

The lowest score comes first; equal scores are resolved alphabetically by the secondary key.

Try it yourself

Sort score records descending by score and ascending by identifier without changing the input order.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which key expresses descending numeric score and ascending name?