Ruby True / False Comparison / sort with <=>

Using the Spaceship operator with TrueClass / FalseClass is not possible normally:

NoMethodError: undefined method '<=>' for true:TrueClass

But we can change this…

Code

module TrueFalseComparison
  def <=>(other)
    raise ArgumentError unless [TrueClass, FalseClass].include?(other.class)
    other ? (self ? 0 : -1) : (self ? 1 : 0)
  end
end

TrueClass.send(:include, TrueFalseComparison)
FalseClass.send(:include, TrueFalseComparison)

Usage

(true <=> false) == 1
(false <=> true) == -1
[true,false,true].sort == [false,true,true]
[true,'x'].sort -> ArgumentError

2 thoughts on “Ruby True / False Comparison / sort with <=>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s