1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Its not exactly true that you can't read the variables from outside of the context. The following will work: a = b.eval('a')
@KennethBaltrinic i wouldn't really call that "reading from outside"; you're just asking the context to read it for you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.