Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class BinaryOperator
- def operate(stack)
- y = stack.pop
- x = stack.pop
- stack.push binary_operate(x, y)
- end
- end
- class Addition < BinaryOperator
- protected
- def binary_operate(x, y)
- x + y
- end
- end
- class Subtraction < BinaryOperator
- protected
- def binary_operate(x, y)
- x - y
- end
- end
- class Multiplication < BinaryOperator
- protected
- def binary_operate(x, y)
- x * y
- end
- end
- class Division < BinaryOperator
- protected
- def binary_operate(x, y)
- x / y
- end
- end
- class Factorial
- def operate(stack)
- stack.push factorial(stack.pop)
- end
- private
- def factorial(i)
- (2..i).inject { |x,y| x * y }
- end
- end
- class OperatorFactory
- def self.create_operator(token)
- case token
- when '+' then Addition.new
- when '-' then Subtraction.new
- when '*' then Multiplication.new
- when '/' then Division.new
- when '!' then Factorial.new
- end
- end
- end
- class Calculator
- def evaluate(*tokens)
- stack = []
- tokens.each do |token|
- if token =~ /\d+/ then
- stack.push token.to_i
- else
- op = OperatorFactory.create_operator token
- op.operate(stack)
- end
- end
- stack.pop
- end
- end
- c = Calculator.new
- puts c.evaluate('2', '3', '+', '!')
Add Comment
Please, Sign In to add comment