2017-04-15 8 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