Ruby 1.9.3 define var with eval

2020-04-21 01:56发布

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条回答
疯言疯语
2楼-- · 2020-04-21 02:09

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.

查看更多
登录 后发表回答