2017-04-15 27 views
2

是否可以聲明使用define_method的動態方法,該方法對具有參數的塊執行instance_exec?事情是這樣的:創建採用自變量的動態方法

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) 
+0

請兩個空格縮進代碼:) –

+1

它做,對不起爲^^ – tomatediabolik

回答

5

是的,你可以:

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 
+0

爲什麼有必要從子類'Struct.new(:C)'? –

+0

不是。這是爲了表明賦予'D.adapt'的塊可以訪問'D'的實例變量。 – Gaston

+0

工程就像一個魅力,非常感謝你! – tomatediabolik