Skip to content

Instantly share code, notes, and snippets.

@jakeonrails
Created January 25, 2014 00:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakeonrails/8609815 to your computer and use it in GitHub Desktop.
Save jakeonrails/8609815 to your computer and use it in GitHub Desktop.
Reverse Polish Notation parser
require 'spec_helper'
class Parser
def parse(string)
stack = []
tokens = string.split(' ')
tokens.each do |token|
if token =~ /\d/
value = token.to_i
stack.push(value)
else
raise "Not enough values" if stack.count < 2
operand = token.to_sym
left, right = stack.pop(2)
stack.push(left.send(token, right))
end
end
raise "Too many values" if stack.count > 1
stack.first
end
end
describe Parser do
let(:parser) { Parser.new }
it 'handles 2 numbers' do
parser.parse('4 2 +').should == 4 + 2
parser.parse('4 2 /').should == 4 / 2
parser.parse('4 2 *').should == 4 * 2
parser.parse('4 2 -').should == 4 - 2
end
it 'handles complex expressions' do
parser.parse('5 1 2 + 4 * + 3 -').should == 14
parser.parse('1 2 + 3 * 4 +').should == 13
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment