Class: QuectoCalc

Inherits:
Object
  • Object
show all
Defined in:
lib/quecto_calc.rb,
lib/quecto_calc/version.rb

Overview

A simple calculator that evaluates primitive arithmetic expressions represented in a text form.

Supported operators:

+ -- add a number
- -- subtract a number.

Supported types:

Integer;
Constant (a string placeholder for an Integer).

Parser/lexer stuff was inspired by the David Callanan’s “Make Your Own Programming Language” series @ github.com/davidcallanan/py-myopl-code

Constant Summary collapse

VERSION =
"0.2.0"

Instance Method Summary collapse

Instance Method Details

#evaluate(expr, consts = {}) ⇒ Object

Evaluate an expression.

Parameters:

  • expr (String)

    Expression (in a text form) to parse and evaluate.

  • [Hash{ (Hash)

    a customizable set of options



32
33
34
35
36
37
# File 'lib/quecto_calc.rb', line 32

def evaluate(expr, consts = {})
  parser = QuectoParser.new

  ast = parser.parse_expr(expr)
  evaluate_ast(ast, consts) if ast
end

#evaluate_ast(ast, consts = {}) ⇒ Object

Evaluate expression from the AST.

Parameters:

  • ast (QuectoParser::NumberNode, QuectoParser::BinOpNode)

    Expression (in a form of AST) to evaluate.

  • [Hash{ (Hash)

    a customizable set of options



48
49
50
51
52
53
# File 'lib/quecto_calc.rb', line 48

def evaluate_ast(ast, consts = {})
  evaluator = Evaluator.new(consts)
  evaluator.visit(ast)
rescue QuectoCalcError, NoMethodError => e
  puts "[#{e.class}] #{e.message}"
end