加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby中的堆栈级别太深

发布时间:2020-12-16 22:50:10 所属栏目:百科 来源:网络整理
导读:class MyClass def method_missing(name,*args) name = name.to_s 10.times do number = rand(100) end puts "#{number} and #{name}" end end 您好,我正在运行ruby但是在这个非递归函数中,当使用这段代码时,我得到堆栈级别太深的错误. x = MyClass.Newx.try
class MyClass
  def method_missing(name,*args)
    name = name.to_s
    10.times do
      number = rand(100)
    end
    puts "#{number} and #{name}"
  end  
end

您好,我正在运行ruby但是在这个非递归函数中,当使用这段代码时,我得到堆栈级别太深的错误.

x = MyClass.New
x.try

解决方法

代码的问题是在times()内定义的数字变量不属于method_missing()范围.因此,当执行该行时,Ruby会将其解释为对self的方法调用.

在正常情况下,您应该获得NoMethodError异常.但是,由于您已经为MyClass重写了method_missing()方法,因此不会出现此异常.相反,直到堆栈溢出方法调用number().

要避免此类问题,请尝试指定允许的方法名称.例如,假设您只需要在MyClass上调用try,test和my_method方法,然后在method_missing()上指定这些方法名称以避免此类问题.

举个例子 :

class MyClass
  def method_missing(name,*args)
    name = name.to_s
    super unless ['try','test','my_method'].include? name
    number = 0
    10.times do
      number = rand(100)
    end
    puts "#{number} and #{name}"
  end  
end

如果你真的不需要method_missing(),请避免使用它.有一些很好的替代品here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读