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 am exercising ruby but in this nonrecursive function i am getting stack level too deep error when use this piece of code.
x = MyClass.New
x.try
The problem with your code is the
numbervariable defined insidetimes()falls out ofmethod_missing()scope. Thus, when that line is executed Ruby interprets it as a method call onself.In normal cases you should be getting
NoMethodErrorexception. However, since you have overridenmethod_missing()method forMyClass, you do not get this exception. Instead until the stack overflows methodnumber() is called.To avoid such problems,try to specify the method names that are allowed. For instance, lets say you only need
try, test, and my_methodmethods to be called onMyClass, then specify these method names onmethod_missing()to avoid such problems.As an example :
If you do not really need
method_missing(), avoid using it. There are some good alternatives here.