Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 948
Pryton Test Avatar asked Mar 17 '12 04:03

Pryton Test


1 Answers

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.

like image 156
emre nevayeshirazi Avatar answered Nov 02 '22 22:11

emre nevayeshirazi