From: "List.rb" Date: 2009-02-03T09:12:13+09:00 Subject: Re: Is this possible in Ruby On Feb 2, 2009, at 6:33 PM, "Sean O'Halpin" wrote: > On Mon, Feb 2, 2009 at 10:49 PM, Damjan Rems wrote: >> >> Just an idea which may come in handy. Can this be done and how in >> Ruby. >> >> def calc(what) >> some_eval(what) >> end >> >> a=10 >> b=12 >> calc('a+b') # expression as parameters >> => 12 # would return >> >> a='aa' >> b='bb' >> calc('a+b') >> => 'aabb' >> >> This is of course strictly hypothetical. I would like the >> expression to >> be evaluated inside the method using variables which are local to the >> calling part. >> >> >> by >> TheR > > ruby 1.9 comes with Binding#eval. In 1.8.6 you can do this: > > class Binding > def eval(str) > Kernel.eval(str, self) > end > end > > a = 10 > b = 12 > binding.eval('a + b') # => 22 > > def another(c, d) > binding.eval('c + d') > end > another(20, 22) # => 42 > > Regards, > Sean > I thought in 1.8.6 it could be done.. Not positive though a, b = 3, 5 formula="a*b" p eval(formula)