2011-09-19 53 views
2

guys。我創建了一個類:instance_eval,define_method和method_missing

class A 
    def initialize &b 
    instance_eval &b 
    end 

    def method_missing method_id, *args 
    self.define_method(method_id) { puts args.first } 
    end 
end 

b = A.new { new_method "oops" } 

但就是不起作用

SystemStackError: stack level too deep 

爲什麼?

+0

你可以在method_missing的添加跟蹤或斷點揣摩自己的問題是什麼... – mb14

+0

當添加一些日誌語句代碼,你會看到define_method沒有爲實例定義,因此遞歸。在調用define_method之前爲#{method_id}「開始添加'p'Begin method_missing時,您將記錄很多行:'Begin method_missing for define_method' – mliebelt

+0

Thanks guys,all works! – avy

回答

6

define_method沒有爲A的實例定義,所以當你調用self.define_method時再次cal method_missing,再次出現=>堆棧溢出。

你需要做這樣的事情,而不是

class A 
    def initialize &b 
     instance_eval &b 
    end 

    def method_missing(method_id, *args) 
     self.class.instance_eval do 
     define_method(method_id) { debugger; puts args.first } 
     end 
    end 
    end 
+0

感謝您的回答! – avy

+0

你可以看看[this](http://stackoverflow.com/questions/900419/how-to-understand-the-difference-between-class-eval-and-instance-eval) – mb14

+0

@avy它可能將這些方法作爲單例方法添加更安全(例如它是線程安全的)。你真的需要爲每個實例添加的方法嗎? – Kelvin