ruby - instance_eval、define_method 和 method_missing

标签 ruby

伙计们。我创建了一个类:

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

为什么?

最佳答案

define_method 没有为 A 的instance 定义,所以当你再次调用 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

关于ruby - instance_eval、define_method 和 method_missing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7471087/

相关文章:

html - ruby 转储对象到 html 格式的字符串

ruby - heroku 上的 API 轮询机器人

ruby - 如何使用 Rack::Test 发送多维数组

ruby-on-rails - 使用 jquery 的 Rails 自动保存表单

ruby-on-rails - Rails 服务器启动后退出

Ruby string.scan(/#{regexp_pattern}/) - 执行时间

ruby - 减少 RSpec 中的代码重复

ruby - 在 Ruby 中优化 "Multidimensional"数组

mysql - ruby 在 mysql 中为列类型 'time' 添加日期 2000-01-01

ruby-on-rails - 使用:method => delete in button_to?的目的是什么