[Awesome Ruby Gem] Use dentaku gem to parse and evaluate math and logic formula
dentaku
Dentaku is a parser and evaluator for a mathematical and logical formula language that allows runtime binding of values to variables referenced in the formulas. It is intended to safely evaluate untrusted expressions without opening security holes.
Installation
You can install it as a gem:
1  gem install dentaku 
or add it into a Gemfile (Bundler):
1  # Gemfile 
Then, run bundle install
.
1  bundle install 
EXAMPLE
This is probably simplest to illustrate in code:
1  calculator = Dentaku::Calculator.new 
Okay, not terribly exciting. But what if you want to have a reference to a variable, and evaluate it at runtime? Here’s how that would look:
1  calculator.evaluate('kiwi + 5', kiwi: 2) 
To enter a case sensitive mode, just pass an option to the calculator instance:
1  calculator.evaluate('Kiwi + 5', Kiwi: 2, kiwi: 2) 
You can also store the variable values in the calculator’s memory and then evaluate expressions against those stored values:
1  calculator.store(peaches: 15) 
For maximum CS geekery, bind is an alias of store.
Dentaku understands precedence order and using parentheses to group expressions to ensure proper evaluation:
1  calculator.evaluate('5 + 3 * 2') 
The evaluate method will return nil
if there is an error in the formula. If this is not the desired behavior, use evaluate!, which will raise an exception.
1  calculator.evaluate('10 * x') 
Dentaku has builtin functions (including if, not, min, max, sum, and round) and the ability to define custom functions (see below). Functions generally work like their counterparts in Excel:
1  calculator.evaluate('SUM(1, 1, 2, 3, 5, 8)') 
round can be called with or without the number of decimal places:
1  calculator.evaluate('round(8.2)') 
round follows rounding rules, while roundup and rounddown are ceil and floor, respectively.
If you’re too lazy to be building calculator objects, there’s a shortcut just for you:
1  Dentaku('plums * 1.5', plums: 2) 
PERFORMANCE
The flexibility and safety of Dentaku don’t come without a price. Tokenizing a string, parsing to an AST, and then evaluating that AST are about 2 orders of magnitude slower than doing the same math in pure Ruby!
The good news is that most of the time is spent in the tokenization and parsing phases, so if performance is a concern, you can enable AST caching:
1  Dentaku.enable_ast_cache! 
After this, Dentaku will cache the AST of each formula that it evaluates, so subsequent evaluations (even with different values for variables) will be much faster – closer to 4x native Ruby speed. As usual, these benchmarks should be considered rough estimates, and you should measure with representative formulas from your application. Also, if new formulas are constantly introduced to your application, AST caching will consume more memory with each new formula.
BUILTIN OPERATORS AND FUNCTIONS
Math: +, , *, /, %, ^, , &
Also, all functions from Ruby’s Math module, including SIN, COS, TAN, etc.
Comparison: <, >, <=, >=, <>, !=, =,
Logic: IF, AND, OR, NOT, SWITCH
Numeric: MIN, MAX, SUM, AVG, COUNT, ROUND, ROUNDDOWN, ROUNDUP
Selections: CASE (syntax see spec)
String: LEFT, RIGHT, MID, LEN, FIND, SUBSTITUTE, CONCAT, CONTAINS
Collection: MAP, FILTER, ALL, ANY, PLUCK
RESOLVING DEPENDENCIES
If your formulas rely on one another, they may need to be resolved in a particular order. For example:
1  calc = Dentaku::Calculator.new 
In the example, annual_income needs to be computed (and stored) before income_taxes.
Dentaku provides two methods to help resolve formulas in order:
Calculator.dependencies
Pass a (string) expression to Dependencies and get back a list of variables (as :symbols) that are required for the expression. Dependencies also takes into account variables already (explicitly) stored into the calculator.
1  calc.dependencies("monthly_income * 12") 
Calculator.solve! / Calculator.solve
Have Dentaku figure out the order in which your formulas need to be evaluated.
Pass in a hash of {eventual_variable_name: “expression”} to solve!
and have Dentaku resolve dependencies (using TSort) for you.
Raises TSort::Cyclic
when a valid expression order cannot be found.
1  calc = Dentaku::Calculator.new 
solve!
will also raise an exception if any of the formulas in the set cannot be evaluated (e.g. raise ZeroDivisionError
). The nonbang solve method will find as many solutions as possible and return the symbol :undefined
for the problem formulas.
INLINE COMMENTS
If your expressions grow long or complex, you may add inline comments for future reference. This is particularly useful if you save your expressions in a model.
1  calculator.evaluate('kiwi + 5 /* This is a comment */', kiwi: 2) 
Comments can be single or multiline. The following are also valid.
1  /* 
EXTERNAL FUNCTIONS
I don’t know everything, so I might not have implemented all the functions you need. Please implement your favorites and send a pull request! Okay, so maybe that’s not feasible because:

You can’t be bothered to share

You can’t wait for me to respond to a pull request, you need it NOW()

The formula is the secret sauce for your startup
Whatever your reasons, Dentaku supports adding functions at runtime. To add a function, you’ll need to specify a name, a return type, and a lambda that accepts all function arguments and returns the result value.
Here’s an example of adding a function named POW that implements exponentiation.
1  > c = Dentaku::Calculator.new 
Here’s an example of adding a variadic function:
1  > c = Dentaku::Calculator.new 
(However both of these are already builtin – the ^ operator and the MAX function)
Functions can be added individually using Calculator#add_function, or en masse using Calculator#add_functions.
FUNCTION ALIASES
Every function can be aliased by synonyms. For example, it can be useful if your application is multilingual.
1  Dentaku.aliases = { 
Also, if you need threadsafe aliases you can pass them to Dentaku::Calculator initializer:
1  aliases = { 
References
[1] rubysolo/dentaku: math and logic formula parser and evaluator  https://github.com/rubysolo/dentaku
[2] dentaku  RubyGems.org  your community gem host  https://rubygems.org/gems/dentaku/