# ruby calculator

## Purpose

I thought about a calculator algorithm that can perform + (addition),-(subtraction), * (multiplication),/(division) with ruby. The most famous way to make a calculator algorithm is (1) Receive the given formula → (2) Convert to reverse Polish notation → (3) Calculate and return the calculation result. This time, I will introduce my own way of thinking from ② to ③. As a matter of fact, I am a beginner myself, so please point out any mistakes.

## Algorithm concept and its code

##### 1. Receive in the standard input of the formula expressed in Reverse Polish Notation.
``````input = gets.chomp.split(" ")
``````
• Reverse Polish notation (postfix notation) is a formula that puts an operator after a number, such as 1 2 + or 2 6 *. By the way, what we usually see is infix notation, such as 1 + 2 or 2 * 6 with the operator in the middle.
##### 2. Create an array of operators in advance to determine whether it is an operator later. At the same time, create a stack to store numerical values.
``````operator = ['+','-','*','/']
num_stack = []
``````
##### 2. Loop the received calculation formula, push it to the stack when a numerical value arrives, pop two numerical values ​​in the stack when an operator arrives, perform each operation, and push the calculation result to the stack.
``````input.each do |s|
#If you get a number, put it on the stack (using a regular expression).
if s =~ /[0-9]/
num_stack << s
end
#If an operator comes, take two numbers from the stack and calculate according to each operator.
if operator.include?(s)
a = num_stack.pop
b = num_stack.pop
a = a.to_i
b = b.to_i
case s
when '+'
num_stack << b + a
when '-'
num_stack << b - a
when '*'
num_stack << b * a
when '/'
num_stack << b / a
end
end
end
``````
##### 3. The last remaining number on the stack is the calculation result.
``````ans = num_stack.pop
puts ans
``````