I have a database of "formulas" stored as strings. For simplicity, suppose that each formula contains 2 variables, denoted by a and b, and that the formulas are all well-formed, and it is ensured that it consists only of characters from the set ()ab+-*
.
At run time, formulas are retrieved from this database, and numerical values for a and b are selected from another source, and formulas are calculated. The assessment can be programmed as follows:
formula = fetch_formula(....)
a = fetch_left_arg(....)
b = fetch_right_arg(....)
result = eval(formula)
This design works, but I'm not quite happy with it. This requires my program to call the free variables exactly the same as they are named in the formula, which is ugly.
If my “formula” is not a string, but a Proc or Lambda object that takes two parameters, I could do something like
result = fetch_proc(...).call(fetch_left_arg(....),fetch_right_arg(....))
but unfortunately the formulas must be strings.
I tried to experiment as follows: what if the method that extracts the formula from the database wraps the string into something that behaves like a block, and where can I pass parameters to it?
block_string = "|a,b| #{fetch_formula(....)}"
Of course, I can’t appreciate such a block_string, but is there something similar that I could use? I know I instance_eval
can pass parameters, but to which object should I apply it? So this may not be an option ....