Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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