Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 在出现StackLevel错误之前,如何确定嵌套函数的数量以及可以使用的数量?_Ruby_Oop - Fatal编程技术网

Ruby 在出现StackLevel错误之前,如何确定嵌套函数的数量以及可以使用的数量?

Ruby 在出现StackLevel错误之前,如何确定嵌套函数的数量以及可以使用的数量?,ruby,oop,Ruby,Oop,我正在读Sandi Metz关于面向对象设计的书,她的主要原则之一是单一责任的思想。下面是她的书中的一个例子,她在书中重构代码来说明这一点 def gear_inches foo = some_intermediate_result * wheel.diameter end 通过这种重构,我如何确定在得到堆栈级错误之前,我可以重构一个单一责任的方法到什么程度?比如说 def gear_inches foo = some_intermediate_result * diameter e

我正在读Sandi Metz关于面向对象设计的书,她的主要原则之一是单一责任的思想。下面是她的书中的一个例子,她在书中重构代码来说明这一点

def gear_inches
  foo = some_intermediate_result * wheel.diameter
end

通过这种重构,我如何确定在得到堆栈级错误之前,我可以重构一个单一责任的方法到什么程度?比如说

def gear_inches
  foo = some_intermediate_result * diameter
end

def diameter
  wheel.diameter * calculation
end

def calculation
  wheel.calculation * another_calculation
end

def another_calculation
  wheel.another_calculation * yet_another_calculation
end

def yet_another_calculation
  wheel.yet_another_calculation
end

等等等等。如何在不滥用单一责任设计的情况下确定嵌套函数的级别?

这将显示一个特定示例中导致堆栈溢出的嵌套调用数:

def my_function a
  my_function(a + 1)
rescue Exception => e
  puts "a is #{a}"
  puts e.message
end

my_function(1)
结果:

a is 8732
stack level too deep
因此,8732次调用后导致堆栈溢出


导致堆栈溢出的嵌套调用的实际数量取决于许多因素(例如,传递的参数等),但一般来说,我认为在手动创建嵌套调用时不需要担心堆栈级别。堆栈溢出通常是由递归调用导致的。

通过这种方式,您不会到达堆栈级别太深。不是没有某种递归/循环逻辑。谢谢,这非常有用。
a is 8732
stack level too deep