Class: Rubulator
- Inherits:
-
Object
show all
- Defined in:
- lib/rubulator.rb,
lib/rubulator/version.rb
Defined Under Namespace
Classes: CalculationError, Variable
Constant Summary
collapse
- VERSION =
'0.1.0'
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
Returns a new instance of Rubulator.
28
29
30
31
32
|
# File 'lib/rubulator.rb', line 28
def initialize
@variables = {}
result.store(0.0)
end
|
Instance Attribute Details
#variables ⇒ Object
Returns the value of attribute variables.
26
27
28
|
# File 'lib/rubulator.rb', line 26
def variables
@variables
end
|
Class Method Details
.calculate(expression) ⇒ Object
34
35
36
|
# File 'lib/rubulator.rb', line 34
def self.calculate(expression)
Rubulator.new.calculate(expression)
end
|
Instance Method Details
#calculate(expression) ⇒ Object
42
43
44
45
46
47
48
49
50
51
52
53
|
# File 'lib/rubulator.rb', line 42
def calculate(expression)
return unless expression && expression != ''
operands = expression.sub(/^\s+/, '').sub(/\s+$/, '').split(/\s+/)
result.store(consume(nil, 'initial', operands).to_f)
unless operands.empty?
raise CalculationError, "Operands #{operands.inspect} left over in expression '#{expression}'"
end
result.to_f
end
|
#constants ⇒ Object
63
64
65
|
# File 'lib/rubulator.rb', line 63
def constants
MATH_CONSTANTS.keys.map(&:to_s)
end
|
#functions ⇒ Object
59
60
61
|
# File 'lib/rubulator.rb', line 59
def functions
MATH_FUNCTIONS
end
|
#operators ⇒ Object
55
56
57
|
# File 'lib/rubulator.rb', line 55
def operators
['='] + OPERATORS
end
|
#result ⇒ Object
38
39
40
|
# File 'lib/rubulator.rb', line 38
def result
@variables[RESULT_VARIABLE] ||= Variable.new(RESULT_VARIABLE)
end
|
#variable_names ⇒ Object
67
68
69
|
# File 'lib/rubulator.rb', line 67
def variable_names
variables.keys.map { |v| VARIABLE_PREFIX + v }
end
|