Why do I get “stack level too deep” from method_missing in irb 1.9.3?

吃可爱长大的小学妹 提交于 2019-12-23 18:05:50

问题


Scenario:

-bash-3.2$ irb -f
ruby-1.9.3-p0 :001 > @v = {}
 => {} 
ruby-1.9.3-p0 :002 > def method_missing(sym, *args); @v[sym]; end
 => nil 
ruby-1.9.3-p0 :003 > a
(irb):2: stack level too deep (SystemStackError)
-bash-3.2$ 

I ran with -f to avoid loading any irbrc stuff. I'm expecting to get nil when I input a. What's going on, and is there a workaround? I tried wrapping a with a begin/rescue Exception block but that didn't do anything.

This also happens with 1.9.2, but not 1.9.1.

More strange behavior:

-bash-3.2$ irb -f
irb(main):001:0> @v = {}
=> {}
irb(main):002:0> def method_missing(sym, *args); @v[sym]; end; 5.times { p a }
nil
nil
nil
nil
nil
=> 5
irb(main):003:0> a
(irb):2: stack level too deep (SystemStackError)
-bash-3.2$ 

This tells me that there's a bug in irb, or that some obscure bug in ruby is being triggered by irb. Also, after defining method_missing, even methods that exist like local_variables or eval cause the error.


回答1:


Looks like defining it as a singleton method works:

def self.method_missing(sym, *args); @v[sym]; end

Defining it as a top-level method replaces BasicObject#method_missing, which probably affected some irb internals like Phrogz said.



来源:https://stackoverflow.com/questions/9491462/why-do-i-get-stack-level-too-deep-from-method-missing-in-irb-1-9-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!