Skip to content

Instantly share code, notes, and snippets.

@mattknox
Created August 14, 2013 17:48
Show Gist options
  • Save mattknox/6233577 to your computer and use it in GitHub Desktop.
Save mattknox/6233577 to your computer and use it in GitHub Desktop.
two different versions of an RPN calculator
OPERATORS = %w{ + - * / }
def tokenize(s)
s.split.map do |x|
if OPERATORS.member? x
x.to_sym
else
x.to_i
end
end
end
def evaluate(s)
stack = []
tokenize(s).each do |x|
y = x
if x.is_a? Symbol
y = stack[1].send x, stack[0]
stack.shift 2
end
stack.unshift y
end
stack
end
puts "evaluate: #{evaluate('1 2 +')}"
def evaluate2(s)
tokenize(s).inject([]) do |stack, x|
if x.is_a? Symbol
x = stack[1].send x, stack[0]
stack.shift 2
end
stack.unshift x
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment