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 number variable defined inside times() falls out of method_missing() scope. Thus, when that line is executed Ruby interprets it as a method call on self.
In normal cases you should be getting NoMethodError exception. However, since you have overriden method_missing() method for MyClass, you do not get this exception. Instead until the stack overflows method number() 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_method methods to be called on MyClass, then specify these method names on 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
If you do not really need method_missing(), avoid using it. There are some good alternatives here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With