Reputation: 111
Is it possible to declare dynamic methods with define_method
that does an instance_exec
of a block with arguments ? Something like this :
class D
def self.adapt (method,*args,&impl)
define_method(method) do
instance_exec(args,impl)
end
end
end
D.adapt(:foo,a,b) { a + b }
puts D.new.foo(1,2)
Upvotes: 2
Views: 68
Reputation: 1848
Yes, you can:
class D < Struct.new(:c)
def self.adapt (method, &impl)
define_method(method) do |*args|
instance_exec(*args, &impl)
end
end
end
D.adapt(:foo) { |a, b| a + b + c }
puts D.new(3).foo(1, 2)
# => 6
Upvotes: 5