Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison operator `<=>` and booleans [closed]

Tags:

ruby

The <=> operator does not handle booleans well.

true <=> true # => 0
true <=> false # => nil

Is this behavior intended by design or am I missing something? I expect:

true <=> false # => 1
false <=> true # => -1

Edit This is what I was looking for:

false.to_i <=> true.to_i # => -1
like image 847
Chapley Watson Avatar asked Nov 19 '25 01:11

Chapley Watson


2 Answers

The <=> operator isn't really a "combined boolean"; it is for ordering items of the same class, if they have an order defined. Numbers are ordered; 1 is greater than 0 and 0 is less than 8675309. Boolean values don't have an inherent order; true isn't greater than false or vice versa.

like image 160
benzado Avatar answered Nov 21 '25 16:11

benzado


They are not the same class. true is a singleton of TrueClass, while false is a singleton of FalseClass. You're comparing apples and oranges (or, in true <=> true case, an apple with the same apple).

For curiosity's sake, why do you think true <=> false should equal 1? EDIT: beaten to it by sawa

like image 40
Amadan Avatar answered Nov 21 '25 16:11

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!