Ruby 1.9.3 define var with eval

我的梦境 提交于 2019-12-04 05:25:41

问题


I am writing something like REPL in Ruby and I need to define vars on the run. I figured it out that I should use eval, but here is excerpt from irb session to test it. In 1.9.3 (That would work in 1.8)

> eval 'a = 3'
=> 3
> a
=> NameError: undefined local variable or method `a' for main:Object

They changed it in 1.9 to:

> eval 'a = 3'
=> 3 
> eval 'a'
=> 3

So seems like changed it since 1.9. How can I define vars in 1.9.3 using eval (or something similar)?


回答1:


IRB is lying to you. This as a script:

eval 'a = 3'
puts a

fails the same way under 1.8.7 and 1.9.3 for me.

Unfortunately the equivalent mentioned both by you and in that answer,

eval 'a = 3'
eval 'puts a'

still doesn't work in 1.9 as a script, though it does work in 1.8.

This, however, works for me in both:

b = binding
b.eval 'a = 3'
b.eval 'puts a'

Using the same binding means variable assignments all happen in the same context. You won't be able to read them from the outside since locals are bound at compile-time, but if you're writing a REPL, "compile-time" is just "when I get another line and eval it" which is fine.



来源:https://stackoverflow.com/questions/14404198/ruby-1-9-3-define-var-with-eval

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