Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dpk
Last active December 11, 2015 21:09
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 dpk/4660307 to your computer and use it in GitHub Desktop.
Save dpk/4660307 to your computer and use it in GitHub Desktop.
A magnitude-comparison monkey-patch for Ruby's case. Suggested at http://swhack.com/logs/2013-01-28#T23-17-31
# usage:
#
# case compare(2,3)
# when :>
# puts "greater"
# when :<
# puts "less"
# when :==
# puts "same"
# end
# # => prints "less"
#
# you can have any number of numbers in the compare expression
class CaseComparer
def initialize *ns
@numbers = ns
end
def === comparer
@numbers.each_cons(2).all? {|x, y| x.method(comparer).call(y) }
end
end
# ugh
class Symbol
@@oldtripeq = method :===
def === *args, &block
x = args.first
if x.is_a? CaseComparer
x === self
else
@@oldtripeq.call *args, &block
end
end
end
def compare *ns; CaseComparer.new *ns; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment