Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module TrueFalseComparison
# Enable TrueClass and FalseClass values to be comparable.
# TrueClass values are valued higher than FalseClass values.
#
# See this article for more info:
# http://grosser.it/2010/07/30/ruby-true-false-comparison-with/
#
# Yes, this is evil monkey-patching. The alternative is much, much worse:
#
# [false, true, false].sort {|a, b| a ? (b ? 0 : -1) : (b ? 1 : 0) }
# => [true, false, false]
#
def <=>(other)
unless [TrueClass, FalseClass].include? other.class
raise ArgumentError, "comparison of #{self} with #{other} failed"
end
self ? (other ? 0 : -1) : (other ? 1 : 0)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment