Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this eval not work in Ruby

Tags:

ruby

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.

like image 317
Anil Avatar asked Jun 11 '12 04:06

Anil


1 Answers

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 
like image 200
matt Avatar answered Oct 16 '22 06:10

matt