Created
May 24, 2012 18:20
-
-
Save nickhoffman/2783270 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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