class UtcRpnCalc::Calculator
Constants
- FFFF
Public Class Methods
new(input)
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 10 def initialize(input) @inputs = input.gsub('X', '^').split @stack = [] end
Public Instance Methods
calculate()
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 15 def calculate @inputs.each do |input| return ERROR unless acceptable_input?(input) process_input(input) end calculated_value.to_formatted_hex end
Private Instance Methods
acceptable_input?(input)
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 26 def acceptable_input?(input) input.valid_number? || has_necessary_operands?(input) end
calculated_value()
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 34 def calculated_value @stack.pop || 0 end
compute(operation)
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 46 def compute(operation) operation.negation_operation? ? compute_negation : compute_with_operands(operation, @stack.pop(2)) end
compute_negation()
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 50 def compute_negation @stack.pop.negate end
compute_with_operands(operation, operands)
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 54 def compute_with_operands(operation, operands) raw_result = operands.first.send(operation, operands.last) valid_result(raw_result) end
has_necessary_operands?(operation)
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 42 def has_necessary_operands?(operation) @stack.length > (operation.negation_operation? ? 0 : 1) end
process_input(input)
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 30 def process_input(input) @stack.push(result(input)) end
result(input)
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 38 def result(input) input.valid_number? ? input.hex : compute(input) end
valid_result(result)
click to toggle source
# File lib/utc_rpn_calc/calculator.rb, line 59 def valid_result(result) if result > FFFF FFFF elsif result < 0 0 else result end end