Skip to content

Instantly share code, notes, and snippets.

@42thcoder
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save 42thcoder/8856254 to your computer and use it in GitHub Desktop.

Select an option

Save 42thcoder/8856254 to your computer and use it in GitHub Desktop.
# 许多特殊情况都没考虑
# 除数为0 优先级 用户输入字母 括号
class Stack
def initialize(size)
@stack = Array.new(size)
@sp = 0
end
def push(value)
@stack[@sp] = value
@sp += 1
end
def pop
return nil if @sp == 0
@sp -= 1
@stack[@sp]
end
def size
@sp
end
def to_string
"#{@sp} elements: #{@stack[0...@sp]}"
end
end
class Calculator
def initialize(input)
@stack = Stack.new(input.length)
input.split().each do |chr|
case chr
when '+', '-', '*', '/'
operate(chr)
else
@stack.push chr.to_i
end
end
end
def operate(operator)
return nil if @stack.size <= 1
so = @stack.pop
fo = @stack.pop
case operator
when '+'
result = fo + so
when '-'
result = fo - so
when '*'
result = fo * so
when '/'
result = fo / so
end
@stack.push result
end
def to_string
@stack.to_string
end
end
puts 'Give me a string'
input = gets
cal = Calculator.new(input)
p cal.to_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment