Ruby中的Kernel#eval和Binding#eval之间的区别

时间:2013-03-26 19:14:54

标签: ruby ruby-2.0

为什么Binding#eval会调用该块,但Kernel#eval不会?

def bar; binding; end
bi = bar {|x| p(x+1)}

bi.eval "yield 2"       # ==> 3
eval "yield 2", binding # ==> LocalJumpError

1 个答案:

答案 0 :(得分:5)

我认为,在第五行,第二个参数必须是'bi':

$ ruby -v
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-linux]

1 def bar; binding; end
2 bi = bar {|x| p(x+1)}
3
4 bi.eval "yield 2"  #==> 3
5 eval "yield 2", bi #==> 3