class Eqn::Calculator

Primary calculator class used for performing calculations or creating eqn instances.

Public Class Methods

new(eqn, vars = {}) click to toggle source
# File lib/eqn/calculator.rb, line 4
def initialize(eqn, vars = {})
  @eqn = eqn
  @vars = vars
end

Private Class Methods

calc(equation, vars = {})
Alias for: calculate
calculate(equation, vars = {}) click to toggle source
# File lib/eqn/calculator.rb, line 65
def calculate(equation, vars = {})
  result = Parser.parse(equation).value(vars)
  raise ZeroDivisionError if result.is_a?(Float) && (result.abs == Float::INFINITY || result.nan?)

  result
end
Also aliased as: calc
valid?(equation, vars = {}) click to toggle source
# File lib/eqn/calculator.rb, line 73
def valid?(equation, vars = {})
  calculate(equation, vars)
  true
rescue EqnError
  false
end

Public Instance Methods

method_missing(method, *args) click to toggle source
Calls superclass method
# File lib/eqn/calculator.rb, line 17
def method_missing(method, *args)
  if delegated_method?(method)
    self.class.send(method, @eqn, @vars)
  elsif match_setter?(method)
    @vars[setter_key(method)] = args.first
  elsif match_getter?(method)
    @vars[getter_key(method)]
  else
    super
  end
end
respond_to_missing?(method, _include_private = false) click to toggle source
Calls superclass method
# File lib/eqn/calculator.rb, line 29
def respond_to_missing?(method, _include_private = false)
  delegated_method?(method) || match_setter?(method) || match_getter?(method) || super
end
set(key_or_hash, value = nil) click to toggle source
# File lib/eqn/calculator.rb, line 9
def set(key_or_hash, value = nil)
  if key_or_hash.is_a?(Hash)
    @vars.merge!(key_or_hash)
  else
    @vars[key_or_hash.to_sym] = value
  end
end

Private Instance Methods

delegated_method?(method) click to toggle source
# File lib/eqn/calculator.rb, line 35
def delegated_method?(method)
  %i(calculate calc valid?).include?(method.to_sym)
end
getter_key(method) click to toggle source
# File lib/eqn/calculator.rb, line 50
def getter_key(method)
  match = method.to_s.match(/^[A-Za-z]+$/)
  return if match.nil?

  key = match.to_s.to_sym
  return unless @vars.key?(key)

  key
end
match_getter?(method) click to toggle source
# File lib/eqn/calculator.rb, line 60
def match_getter?(method)
  !getter_key(method).nil?
end
match_setter?(method) click to toggle source
# File lib/eqn/calculator.rb, line 46
def match_setter?(method)
  !setter_key(method).nil?
end
setter_key(method) click to toggle source
# File lib/eqn/calculator.rb, line 39
def setter_key(method)
  match = method.to_s.match(/^[A-Za-z]+=$/)
  return unless match

  match.to_s.delete('=').to_sym
end