Sorting and comparison

The spaceship operator

Ruby compares with <=>, which answers -1, 0 or 1. Everything that sorts uses it, and a class that defines it can be sorted, compared and put in a range.

sort calls it on pairs; sort_by runs the block once per item and sorts the keys, which is faster and easier to read when the key is not the value itself:

ruby -e 'p ["b", "A", "c"].sort_by(&:downcase)'

["A", "b", "c"]

Sort and sort_by

A plain sort on strings puts capitals before lowercase, because it compares character codes. A sort_by(&:downcase) gives the order a reader expects and keeps the original casing in the result.

ruby -e 'p ["b", "A", "c"].sort; p ["b", "A", "c"].sort_by(&:downcase)'

["A", "b", "c"]
["A", "b", "c"]

Here both lines agree; a list such as ["B", "a"] sorts as ["B", "a"] with sort and as ["a", "B"] with sort_by. Sorting by a key from a hash is the common case: rows.sort_by { |row| row[:name].downcase }.

Sorting text and numbers

A number and its text form sort differently. A list of strings that look like numbers sorts as text, which puts ten before two:

ruby -e 'p [10, 9, 2].sort; p %w[10 9 2].sort'

[2, 9, 10]
["10", "2", "9"]

This is not a Ruby quirk; any language that sorts strings does the same. Convert before sorting when the values are numbers: list.sort_by(&:to_i).

Comparable on your own class

Include Comparable and define <=>, and the class gains <, >, between? and clamp:

Box = Struct.new(:amount) do include Comparable def <=>(other) amount <=> other.amount end end puts [Box.new(2), Box.new(1)].min.amount

ruby box.rb

1

The comparison delegates to the value that decides the order, which keeps the rule in one place. A class with several attributes compares an array of them: [size, name] <=> [other.size, other.name].

What to watch for

sort is stable in Ruby only as a side effect of the algorithm, not as a promise. When ties must keep their input order, include the position in the key: sort_by.with_index { |row, i| [row[:v], i] }.

sort without a block raises ArgumentError as soon as two items cannot be compared, for example a string and a number in one list. The message names the pair, which is usually enough to find the bad row.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does 1 <=> 2 return?

    Answer

    -1

    The left side is smaller, so the spaceship answers -1.

  2. What does this program print? p ["b", "A", "c"].sort

    Answer

    ["A", "b", "c"]

    sort compares character codes, and a capital comes before a lowercase letter.

  3. What does this program print? p ["B", "a"].sort_by(&:downcase)

    Answer

    ["a", "B"]

    The block lowers both keys, so a comes before b and the original casing stays.

  4. What does [10, 9, 2].sort return?

    Answer

    [2, 9, 10]

    Integers sort by value, so 2 is first and 10 last.

  5. What does %w[10 9 2].sort return?

    Answer

    ["10", "2", "9"]

    The elements are strings, so they sort as text and ten comes before two.

  6. How do you sort those strings as numbers?

    Answer

    list.sort_by(&:to_i)

    sort_by takes the integer key, so 2, 9 and 10 come out in number order.

  7. Which methods come from including Comparable and defining <=>?

    Answer

    <, >, between? and clamp

    Comparable derives the comparison methods from the spaceship.

  8. What does this program print? Box = Struct.new(:size) do include Comparable def <=>(other) size <=> other.size end end puts [Box.new(2), Box.new(1)].min.size

    Answer

    1

    min uses <=>, so the box of size 1 is the smallest.

  9. What does [1, "a"].sort raise?

    Answer

    ArgumentError: comparison of Integer with String failed

    The spaceship cannot compare a number with a string, and the message names the pair.

  10. How do you keep the input order of equal items in a sort?

    Answer

    Include the position in the key: sort_by.with_index { |row, i| [row[:v], i] }

    Stability is not a promise of sort, so the index is part of the key.

Article author: Arthur Isaev