Ruby 1.9.3 define var with eval

后端 未结 1 1790
醉酒成梦
醉酒成梦 2021-01-25 15:48

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

相关标签:
1条回答
  • 2021-01-25 16:25

    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.

    0 讨论(0)
提交回复
热议问题