Brian Schröder wrote:
and have the block from the dynamically created method foo be
evaluated in the binding of the instance of A.
I'm sure this is possible, but I've never really grocked eval,
instance_eval and class_eval.
Not sure if this'll help, but it's something I'd thrown together awhile back that attempted to the same sorta thing:
module Kernel
def multidef(name,&blk)
Multidef.new(self,name).instance_eval(&blk)
nil
end
end
class Multidef
def initialize(receiver, name)
@receiver = receiver
name = name.to_s
@name = name
@receiver.send(:define_method,name) do |*a|
send(name+a.size.to_s,*a)
end
end
def args arity, &blk
name = @name
@receiver.send(:define_method,@name+arity.to_s,&blk) #do |*a|
# if a.size != arity then send(name+a.size.to_s,*a)
# else blk.call(*a) end #can I get this to execute in self.binding?
# end
end
end
multidef := do
args 2 do |coord,val|
x,y = convert(coord)
self[x,y] = val
end
args 3 do |x,y,val|
@thing[y] = val
end
end
class Foo
multidef :fun do
args 1 do |a|
puts "one: #{a}"
end
args 2 do |a,b|
puts "two: #{a}, #{b}"
fun a
end
args 3 do |a,b,c|
puts "three: #{a}, #{b}, #{c}"
fun a,b
end
end
end
f = Foo.new
f.fun(1)
f.fun('a','b','c')
f.fun('hello',/nightmare/)
__END__
Problems:
1. super doesn't work across different arities.
2. Can't take blocks.
Devin