R
Robert Klemme
When I couldn't sleep this morning, this came across my head:
class Check
def initialize(sym, args)
@args=args
instance_eval "def ===(obj); obj.#{sym}(*@args); end"
end
class <<self
def create(sym=nil, *args, &bl)
if bl
def bl.===(obj); call(obj); end
bl
elsif sym
new sym, args
else
raise "Need either block or symbol with arguments"
end
end
private :new
end
end
Now you can do:
Negative = Check.create {|x| x.kind_of? Numeric and x<0}
Positive = Check.create {|x| x.kind_of? Numeric and x>0}
Zero = Check.create {|x| x.kind_of? Numeric and x==0}
# error:
begin
Foo = Check.new :foo
raise "No exception!"
rescue NameError
# puts "ok"
end
[-2,-10,23,666,10.4,-23.4,"foo"].each do |i|
case i
when Negative
puts "#{i} Neg"
when Positive
puts "#{i} Pos"
when Zero
puts "#{i} Zero"
else
puts "#{i.inspect} not numeric"
end
end
Empty = Check.create :empty?
for i in 0..10 do
a=Array.new( i, "x" )
case a
when Empty
puts "empty"
else
puts "filled (#{a.inspect})"
end
end
robert
class Check
def initialize(sym, args)
@args=args
instance_eval "def ===(obj); obj.#{sym}(*@args); end"
end
class <<self
def create(sym=nil, *args, &bl)
if bl
def bl.===(obj); call(obj); end
bl
elsif sym
new sym, args
else
raise "Need either block or symbol with arguments"
end
end
private :new
end
end
Now you can do:
Negative = Check.create {|x| x.kind_of? Numeric and x<0}
Positive = Check.create {|x| x.kind_of? Numeric and x>0}
Zero = Check.create {|x| x.kind_of? Numeric and x==0}
# error:
begin
Foo = Check.new :foo
raise "No exception!"
rescue NameError
# puts "ok"
end
[-2,-10,23,666,10.4,-23.4,"foo"].each do |i|
case i
when Negative
puts "#{i} Neg"
when Positive
puts "#{i} Pos"
when Zero
puts "#{i} Zero"
else
puts "#{i.inspect} not numeric"
end
end
Empty = Check.create :empty?
for i in 0..10 do
a=Array.new( i, "x" )
case a
when Empty
puts "empty"
else
puts "filled (#{a.inspect})"
end
end
robert