ruby picture

RCR 327: true and false should be comparable with <=>

Submitted by tirsen (Tue Jan 24 03:56:15 UTC 2006)

Abstract

I can currently not sort booleans which is not "principle of least surprise". That is, it is slightly confusing (to me but maybe not to Matz).

Problem

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

Makes me confused...

Proposal

 >> [true, false, true].sort                                                     
 => [false, true, true]                                                          

or

 >> [true, false, true].sort                                                     
 => [true, true, false]                                                          

Analysis

Sorry for not describing this in more detail, but it's really so simple. :-)

Implementation

 class FalseClass
   def <=>(other)
     other ? -1 : 0
   end
 end
 class TrueClass
   def <=>(other)
     other ? 0 : 1
   end
 end

Or the other way around. I'm sure there's a more elegant implementation.

ruby picture
Comments Current voting
This will probably be completely rejected because you have brought up "least surprise." Please look on ruby-talk to see why that's bad. It will also be rejected because there is no meaningful sort to true and false and Matz has indicated this on ruby-talk in the past. Your RCR suggests that the sort order is flexible, so why should Matz choose one order over another?

If you find in your code that you have a heterogeneous collection that you want to sort and it contains Boolean values, then you may want to use #sort_by instead of #sort. -- Austin Ziegler


As Austin stated, you need a good reason more than POLS. If you won't come up with any reason why True is bigger than False (or vice versa), I would not accept this proposal.

matz.


Strongly opposed 1
Opposed 0
Neutral 0
In favor 0
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .