Ruby: evaluate string with dynamic binding of variables -


i have database of "formulas" stored strings. let's assume simplicity, each formula contains 2 variables denoted , b, , formulas wellformed , ensured consists of characters set ()ab+-*.

at runtime, formulas fetched database, , source, numeric values , b fetched, , formulas evaluated. evaluation can programmed this:

# how works right formula = fetch_formula(....) = fetch_left_arg(....) b = fetch_right_arg(....) result = eval(formula) 

this design works, i'm not entirely happy it. requires program names free variables same named in formula, ugly.

if "formula" not string, proc object or lambda accepts 2 parameters, like

# no explicitly named variables result = fetch_proc(...).call(fetch_left_arg(....),fetch_right_arg(....)) 

but unfortunately, formulas have strings.

i tried experiment in following way: if method, fetches formula database, wrap string something, behaves block, , pass parameters it?

# not work of course, maybe idea: block_string = "|a,b| #{fetch_formula(....)}" 

of course can't eval such block_string, there similar use? know instance_eval can pass parameters, object should apply to? perhaps not option either....

one way avoid creating variables in local scope use binding:

bind = binding formula = fetch_formula(....) bind.local_variable_set :a, fetch_left_arg(....) bind.local_variable_set :b, fetch_right_arg(....) result = bind.eval(formula) 

the variables a , b exist in binding, , not pollute rest of code.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -