【问题标题】:Stack Level Too Deep, but unsure what is exactly causing the infinite recursion堆栈级别太深,但不确定究竟是什么导致了无限递归
【发布时间】:2012-04-19 02:10:29
【问题描述】:

所以我对此的研究似乎表明这里有一些东西导致了无限递归,但我不确定它是什么。谁能指出我做错了什么?

def initialize(_val)
    @start_value = _val
end

def method_missing(method, *args)
    if method.starts_with?("plus") then
        num = method[4 .. method.length]
        if (/^[\d]+(\.[\d]+){0,1}$/ === num) then
            number = Integer(num)
            self.class_eval("def #{method}; return @start_value + x; end")
        self.plus(number)
        else
            super.method_missing
        end
    else
        super.method_missing
    end
end

end

【问题讨论】:

  • 这很奇怪。我希望您的代码立即抛出 NoMethodError 以在符号上调用 starts_with?。此外,您使用 super 错误 - 它应该只是 super。通过添加.method_missing,您在调用超类的method_missing 的结果上调用method_missing

标签: ruby


【解决方案1】:

你不应该这样做:

super.method_missing

你想要这个:

super

在这两种情况下,您都将使用不带参数的super,这是调用祖先版本方法的正确方法,在本例中为method_missing。但是在您的版本中,您会在结果上冗余地调用method_missing,这就是它变得无限的地方。

【讨论】:

    【解决方案2】:

    最明显的解释是如果您没有将plus 定义为实例方法。但是为什么不在 method_missing 方法的顶部添加 puts method 以便您可以看到发生了什么?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多