Created
January 25, 2014 00:38
-
-
Save jakeonrails/8609815 to your computer and use it in GitHub Desktop.
Reverse Polish Notation parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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