J
Joel VanderWerf
This looks kind of cute, as a way to mix class-matching tests with
comparison operator tests in case statements. Too bad it's not really
practical (the commented out caching may help a bit, but may also use
too much memory):
class Comparator < Proc
def ===(val)
call val
end
def &(other)
compare do |val|
self[val] and other[val]
end
end
end
def compare
Comparator.new
end
class Numeric
#@comparator_lt = {}
def self.<(x)
#@comparator_lt[x] ||=
compare do |val|
self === val and val < x
end
end
#@comparator_gt = {}
def self.>(x)
#@comparator_gt[x] ||=
compare do |val|
self === val and val > x
end
end
end
raise unless (Numeric < 6) === 3
raise if (Integer < 6) === 2.3
raise if (Integer < 6) === "foo"
case 3
when (Numeric < 6) & (Numeric > 5); raise
when (Numeric < 0) & (Numeric > -10); raise
when (Numeric < 6) & (Numeric > 2)
else raise
end
comparison operator tests in case statements. Too bad it's not really
practical (the commented out caching may help a bit, but may also use
too much memory):
class Comparator < Proc
def ===(val)
call val
end
def &(other)
compare do |val|
self[val] and other[val]
end
end
end
def compare
Comparator.new
end
class Numeric
#@comparator_lt = {}
def self.<(x)
#@comparator_lt[x] ||=
compare do |val|
self === val and val < x
end
end
#@comparator_gt = {}
def self.>(x)
#@comparator_gt[x] ||=
compare do |val|
self === val and val > x
end
end
end
raise unless (Numeric < 6) === 3
raise if (Integer < 6) === 2.3
raise if (Integer < 6) === "foo"
case 3
when (Numeric < 6) & (Numeric > 5); raise
when (Numeric < 0) & (Numeric > -10); raise
when (Numeric < 6) & (Numeric > 2)
else raise
end