Skip to content

Instantly share code, notes, and snippets.

@nickhoffman
Created May 24, 2012 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickhoffman/2783270 to your computer and use it in GitHub Desktop.
Save nickhoffman/2783270 to your computer and use it in GitHub Desktop.
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