Skip to content

Instantly share code, notes, and snippets.

@closer
Created July 4, 2015 02:15
Show Gist options
  • Save closer/0f5f74b4a153936f84a7 to your computer and use it in GitHub Desktop.
Save closer/0f5f74b4a153936f84a7 to your computer and use it in GitHub Desktop.
class RevPolish
def initialize(expression)
@expression = expression.split
@stack = []
end
def result
@expression.each{|n| add n }
raise SyntaxError, @expression unless @stack.size == 1
@stack.last
end
private
def add n
case n
when /\A[+-\/*]\z/ then calcurate n.to_sym
when /\A[0-9]+\z/ then stack n.to_i
end
p @stack
self
end
def stack operand
@stack.push operand
end
def calcurate operator
@stack.push( -> n { @stack.pop.send operator, n }.call @stack.pop )
end
end
p RevPolish.new(ARGV.shift).result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment