Stack Level Too Deep in Ruby

class MyClass def method_missing(name, *args) name = name.to_s 10.times do number = rand(100) end puts "#{number} and #{name}" end end 

Hello, I do ruby, but in this non-recursive function, I get a stack level too high when using this code snippet.

 x = MyClass.New x.try 
+6
source share
1 answer

The problem with your code is that the variable number , defined inside times() , falls method_missing() scope of method_missing() . Thus, when this line is executed, Ruby interprets it as a method call on self .

In normal cases, you should get a NoMethodError exception. However, since you have exceeded the method_missing() method for MyClass , you will not get this exception. Instead of calling the number( ) method.

To avoid such problems, try specifying the names of the methods that are allowed. For example, let's say you only need the try, test, and my_method that should be called on MyClass , then point these method names to method_missing() to avoid such problems.

As an example:

 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 

Unless you really need method_missing() , do not use it. There are some good alternatives here .

+11
source

Source: https://habr.com/ru/post/910965/


All Articles