Why does this evaluation not work in Ruby

Can you explain this?

I want to evaluate values ​​and calculations from two different sources. One source gives me the following information (programmatically):

'a = 2' 

The second source gives me this expression for evaluation:

 'a + 3' 

It works:

 a = 2 eval 'a + 3' 

This also works:

 eval 'a = 2; a + 3' 

But I really need this, and this does not work:

 eval 'a = 2' eval 'a + 3' 

I would like to understand the difference and how I can do the last option.

Thanks for your help.

+4
source share
1 answer

You can create a Binding and bind the same binding to each eval :

 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 

That way, all the variables you created in previous calls to eval are available later (as long as you use the same binding object).

Instead of using Kernel::eval you can use Binding#eval , which will make the connection more clear:

 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 
+12
source

All Articles