Can you explain this?
I want to eval values and calculations from two different sources. One source gives me the following info(programmatically):
'a = 2'
The second source gives me this expression to evaluate:
'a + 3'
This works:
a = 2
eval 'a + 3'
This also works:
eval 'a = 2; a + 3'
But what I really need is this, and it doesn't work:
eval 'a = 2'
eval 'a + 3'
I would like to understand the difference, and how can I make the last option work.
Thanks for your help.
You could create a Binding
, and associate the same binding with each eval
call:
1.9.3p194 :008 > b = binding
=> #<Binding:0x00000100a60c60>
1.9.3p194 :009 > eval 'a = 2', b
=> 2
1.9.3p194 :010 > eval 'a + 3', b
=> 5
This way any variables that you create in earlier eval
calls are available later on (as long as you use the same binding object).
Instead of using Kernel::eval
, you could use Binding#eval
, which would make the association clearer:
1.9.3p194 :011 > b = binding
=> #<Binding:0x00000100b46aa8>
1.9.3p194 :012 > b.eval 'a = 2'
=> 2
1.9.3p194 :013 > b.eval 'a + 3'
=> 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With