Module: ReversePolishCalculator::Inputs
- Defined in:
- lib/reverse-polish-calculator/inputs.rb
Instance Attribute Summary collapse
-
#swapped ⇒ Object
Returns the value of attribute swapped.
Instance Method Summary collapse
- #add_operand(input) ⇒ Object
- #calculate(aggregate = 0) ⇒ Object
- #calculation ⇒ Object
- #empty_trash ⇒ Object
- #inspect ⇒ Object
- #invoke_binary_operator(input) ⇒ Object
- #invoke_math_method(input) ⇒ Object
Instance Attribute Details
#swapped ⇒ Object
Returns the value of attribute swapped.
4 5 6 |
# File 'lib/reverse-polish-calculator/inputs.rb', line 4 def swapped @swapped end |
Instance Method Details
#add_operand(input) ⇒ Object
24 25 26 27 |
# File 'lib/reverse-polish-calculator/inputs.rb', line 24 def add_operand(input) @operands << input @calculated = false end |
#calculate(aggregate = 0) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/reverse-polish-calculator/inputs.rb', line 6 def calculate(aggregate = 0) @operands, @trash = [], [] @aggregate = aggregate each do |input| if input.operand? add_operand(input) elsif input.math_method? invoke_math_method(input) else invoke_binary_operator(input) end end empty_trash calculation end |
#calculation ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/reverse-polish-calculator/inputs.rb', line 58 def calculation if @calculated if swapped @operands.first else @aggregate + @operands.last.to_f end else @aggregate end end |
#empty_trash ⇒ Object
70 71 72 |
# File 'lib/reverse-polish-calculator/inputs.rb', line 70 def empty_trash delete_if {|input| @trash.include?(input) } end |
#inspect ⇒ Object
74 75 76 |
# File 'lib/reverse-polish-calculator/inputs.rb', line 74 def inspect map(&:to_f).join(', ') end |
#invoke_binary_operator(input) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/reverse-polish-calculator/inputs.rb', line 36 def invoke_binary_operator(input) operand_1 = @operands.pop operand_2 = @operands.pop unless operand_2 self.swapped = true operand_2 = operand_1 operand_1 = @aggregate else self.swapped = false end @operands.push(if @swapped input.invoke(operand_1, operand_2) else input.invoke(operand_2, operand_1) end) @trash << input << operand_1 << operand_2 @calculated = true end |
#invoke_math_method(input) ⇒ Object
29 30 31 32 33 34 |
# File 'lib/reverse-polish-calculator/inputs.rb', line 29 def invoke_math_method(input) operand = @operands.pop || @aggregate @operands.push input.invoke(operand) @trash << input << operand @calculated = true end |