Pryton Test
Pryton Test

Reputation: 63

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 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

Upvotes: 6

Views: 11032

Answers (1)

emre nevayeshirazi
emre nevayeshirazi

Reputation: 19241

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.

Upvotes: 11

Related Questions