2

guys. I create a class:

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" }

But is does not work

SystemStackError: stack level too deep

Why?

avy
  • 572
  • 3
  • 10
  • you could add a trace or a breakpoint in method_missing and try to figure yourself what the problem is ... – mb14 Sep 19 '11 at 12:59
  • When adding some log statements to your code, you will see that define_method is not defined for the instance, therefore the recursion. When adding `p "Begin method_missing for #{method_id}"` before calling the define_method, you will get logged a lot of lines: `Begin method_missing for define_method` – mliebelt Sep 19 '11 at 13:01

1 Answers1

6

define_method is not defined for an instance of A, so when you call self.define_method that cal method_missing again, an again => stack overflow.

You need to do something like that instead

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
mb14
  • 22,276
  • 7
  • 60
  • 102
  • you can have a look at [this](http://stackoverflow.com/questions/900419/how-to-understand-the-difference-between-class-eval-and-instance-eval) – mb14 Sep 19 '11 at 14:17
  • @avy it might be safer for these methods to be added as singleton methods (e.g. it's thread-safe). Do you really need the method added for every instance? – Kelvin Feb 28 '12 at 22:32