Class: Eqn::Calculator

Inherits:
Object
  • Object
show all
Defined in:
lib/eqn/calculator.rb

Overview

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(eqn, vars = {}) ⇒ Calculator

Returns a new instance of Calculator.



4
5
6
7
# File 'lib/eqn/calculator.rb', line 4

def initialize(eqn, vars = {})
  @eqn = eqn
  @vars = vars
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# 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

Class Method Details

.calculate(equation, vars = {}) ⇒ Object Also known as: calc

Raises:



65
66
67
68
69
70
# 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

.valid?(equation, vars = {}) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
76
77
78
# File 'lib/eqn/calculator.rb', line 73

def valid?(equation, vars = {})
  calculate(equation, vars)
  true
rescue EqnError
  false
end

Instance Method Details

#respond_to_missing?(method, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
# 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) ⇒ Object



9
10
11
12
13
14
15
# 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