Search code examples
rubyspaceship-operator

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


In "Is it possible to sort a list of objects depending on if the individual object's response to a method?", I discovered that the flying saucer doesn't work on booleans.

Consider:

Ruby 1.8.7:

[true, false].sort # => undefined method `<=>' for true:TrueClass (NoMethodError)
true <=> false     # => undefined method `<=>' for true:TrueClass (NoMethodError)

Ruby 1.9.3:

[true, false].sort # => comparison of TrueClass with false failed (ArgumentError)
true <=> false     # => nil
true <=> true      # => 0
false <=> true     # => nil

It may have something to do with true and false not having a canonical sort order, because which comes first? But, that sounds pretty weak to me.

Is this a bug in sort?


Solution

  • 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.