Dear all,
I need help in dynamically creating a Proc from a String like, say,
a='f(x)=c*exp(x/k)',
(I need to do this many times for many different formulas)
which I want to use Ruby to calculate as a function of x, given
constants c,k, i.e.,
In this example, I want the following lines to produce,
b=a.generate_formula => "def f(x)\n\n return Proc.new{|c,x,k|
cexp(x/k) }\n end \n"
c=a.eval_formula({‘c’,5.0,‘k’,2.0,‘x’,1.0}) => 5exp(0.5)
The first line is o.k., and I manage to change the string b
to
d=“f(1.0).call(5.0,2.0)”,
but I can’t eval it using
eval(b) # (should make the function available as a Proc method)
eval(d) # (should output the value at x=1.0)
because the first variable,x , doesn’t get its value assigned:
t00.rb:102:in eval_formula': (eval):6:in
/’: nil can’t be coerced into
Float (TypeError)
from (eval):6:in Ie' from (eval):1:in
call’
from (eval):1:in eval_formula' from t00.rb:64:in
eval’
from t00.rb:102:in eval_formula' from t00.rb:64:in
each’
from t00.rb:64:in `eval_formula’
from t00.rb:131
Is there a better way to do this ?
Thank you!
Best regards,
Axel