ruby calculator


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(" ")
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
  #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
3. The last remaining number on the stack is the calculation result.
ans = num_stack.pop
puts ans

Recommended Posts

ruby calculator
Ruby learning 4
[Ruby] Array
Ruby learning 5
Ruby basics
Ruby Review 2
Ruby addition
Refactoring Ruby
Ruby learning 3
Ruby setting 2
Ruby problem ⑦
Ruby learning 2
[Ruby] Block
Refactoring Ruby
Ruby learning 6
Ruby settings 1
Refactoring Ruby
Ruby basics
Ruby memo
Ruby learning 1
Ruby Review 1
[Ruby] Module
Ruby input / output
ruby Uppercase letters
ruby search problem
Ruby Learning # 25 Comments
ruby constant variable
Ruby to_s method
[Ruby] postfix if
[Ruby] FizzBuzz problem
Ruby text conversion
Ruby basic terms
ruby exception handling
Ruby Learning # 13 Arrays
About Ruby symbols
Ruby Learning # 1 Introduction
Ruby Learning # 34 Modules
I started Ruby
[Ruby] Iterative processing
ruby API problem
Ruby vertical writing
Guitar fret calculator
About Ruby Hashes
Ruby setting 3 Rubocop
Ruby Learning # 14 Hashes
[ruby] drill output
[Ruby] each nested
[Ruby] Arithmetic progression
[Ruby] FizzBuzz problem
Ruby Hash notes
Class in Ruby
[Ruby] slice method
Ruby standard output
[Ruby] end_with? method
[Ruby] Method memorandum
Basics of Ruby
[WIP] Ruby Tips
[ruby] drill output
Ruby exception handling
About Ruby arrays
[ruby] Double hash