Skip to content

Instantly share code, notes, and snippets.

@ldunn
Created August 12, 2010 01:19
Show Gist options
  • Select an option

  • Save ldunn/520128 to your computer and use it in GitHub Desktop.

Select an option

Save ldunn/520128 to your computer and use it in GitHub Desktop.
class Parser
def initialize
@ops = ['+', '-', '/', '*']
@position = 0
@terms = []
end
def parse(expr)
@terms = expr.split(' ')
if @terms.length > 2 then
@position = 0
scan_for_op
op = @terms[@position]
apply_op(op)
else
@terms.first.to_f
end
end
def apply_op(op)
result = @terms[@position-2].to_f.send(op.to_sym, @terms[@position-1].to_f)
@terms.delete_at(@position-1)
@terms.delete_at(@position-2)
@position -= 2
@terms[@position] = result.to_s
parse(@terms * " ")
end
def scan_for_op
while (not @ops.member? @terms[@position])
@position += 1
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment