Why doesn't sort or the spaceship (flying saucer) operator (<=>) work on booleans in Ruby?

Boolean values have no natural ordering.

The Ruby language designer(s) probably felt that to invent an ordering for booleans would be a surprise to developers so they intentionally left out the comparison operators.


The so-called flying saucer requires all comparison operators (<, >, ==) to work (not technically, although certainly theoretically). true and false are not less-than or greater-than each other. The same will hold true for nil. For a practical workaround, you can 'cast' to integers (0 for false, 1 for true). Something like:

[true, false, true].sort_by{|e| e ? 1 : 0}

Booleans have no natural ordering. Unlike C, false is not less than true, they're just equivalent and equally valid states. However it is possible to configure the sort any way you like using a block, for example:

ary = [true, false, false, true]
ary.sort {|a,b|  a == b ? 0 : a ? 1 : -1 }

# => [false, false, true, true]

Reversing the order is also trivial:

ary.sort {|a,b|  a == b ? 0 : a ? -1 : 1 }

# => [true, true, false, false]