Last active
December 11, 2015 21:09
-
-
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
This file contains 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
# 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