Class: LatexEval::PostfixNotation
- Inherits:
-
Object
- Object
- LatexEval::PostfixNotation
- Defined in:
- lib/latex_eval/postfix_notation.rb
Instance Attribute Summary collapse
-
#notation ⇒ Object
readonly
Returns the value of attribute notation.
-
#operations ⇒ Object
readonly
Returns the value of attribute operations.
Instance Method Summary collapse
- #eval(subs = {}) ⇒ Object
-
#initialize(notation) ⇒ PostfixNotation
constructor
A new instance of PostfixNotation.
Constructor Details
#initialize(notation) ⇒ PostfixNotation
Returns a new instance of PostfixNotation.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/latex_eval/postfix_notation.rb', line 5 def initialize(notation) @notation = notation @operations = { add: { args: 2, operation: ->(a,b) { a + b }, }, subtract: { args: 2, operation: ->(a,b) { a - b }, }, multiply: { args: 2, operation: ->(a,b) { a * b }, }, divide: { args: 2, operation: ->(a,b) { a / b }, }, power: { args: 2, operation: ->(a,b) { a ** b }, }, mod: { args: 2, operation: ->(a,b) { a % b }, }, negative: { args: 1, operation: ->(a) { -a }, }, positive: { args: 1, operation: ->(a) { +a }, }, } end |
Instance Attribute Details
#notation ⇒ Object (readonly)
Returns the value of attribute notation.
3 4 5 |
# File 'lib/latex_eval/postfix_notation.rb', line 3 def notation @notation end |
#operations ⇒ Object (readonly)
Returns the value of attribute operations.
3 4 5 |
# File 'lib/latex_eval/postfix_notation.rb', line 3 def operations @operations end |
Instance Method Details
#eval(subs = {}) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/latex_eval/postfix_notation.rb', line 43 def eval(subs = {}) stack = [] notation.each do |elem| if elem.is_a? Symbol if operations.has_key? elem stack.push operations[elem][:operation].call(*stack.pop(operations[elem][:args])).to_f else stack.push subs[elem].to_f end else stack.push elem.to_f end end return stack.first end |