Skip to content

Instantly share code, notes, and snippets.

@dpk dpk/gist:4660307

Last active Dec 11, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.