Skip to content

Instantly share code, notes, and snippets.

@manveru
Created July 16, 2010 03:37
Show Gist options
  • Save manveru/477890 to your computer and use it in GitHub Desktop.
Save manveru/477890 to your computer and use it in GitHub Desktop.
RPN Calculator
# Simple RPN calculator with stack.
# Example usage:
# >> 400 400 400 *
# Top of stack: 64000000
# >> 40 40 *
# Top of stack: 102400000000
# >> 40
# Top of stack: 40
# >> 30
# Top of stack: 30
# >> +
# Top of stack: 102400000070
require 'readline'
require 'strscan'
stack = []
while line = Readline.readline('>> ', true)
next if line.empty?
scanner = StringScanner.new(line)
until scanner.eos?
if scanner.scan(/([+-]?[0-9]+\.[0-9]+)/)
stack << scanner[1].to_f
elsif scanner.scan(/([+-]?(?:0|[1-9])[0-9]*)/)
stack << scanner[1].to_i
elsif scanner.scan(%r(([*/+-])))
operand = scanner[1]
stack = [stack.inject{|sum, value| sum.send(operand, value) }]
elsif scanner.scan(/\s+/)
end
end
puts "Top of stack: %p" % [stack.last]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment