Skip to content

Instantly share code, notes, and snippets.

@terabyte128
Last active October 30, 2019 20:09
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 terabyte128/def7c676029da139b8201a9e67e8e2ee to your computer and use it in GitHub Desktop.
Save terabyte128/def7c676029da139b8201a9e67e8e2ee to your computer and use it in GitHub Desktop.
A simple Reverse Polish Notation calculator written in Ruby. Equations can be entered interactively or as arguments.
def update_stack(stack, arg)
if /-?\d+(\.\d+)?/.match arg
stack.push arg.to_f
else
i1 = stack.pop
i2 = stack.pop
begin
result = i1.send(arg, i2)
stack.push result
rescue => exception
if @interactive
puts "Bad argument! Try again."
stack.push i2 if !i2.nil?
stack.push i1 if !i1.nil?
else
puts "Bad arguments! Check your syntax."
exit
end
end
end
end
def interactive
stack = []
puts "Interactive mode: enter numbers or operators seperated by newlines, or x to exit."
loop do
cur = gets.chomp
exit if cur == "x"
update_stack(stack, cur)
puts stack.inspect
end
end
def all_at_once arr
stack = []
arr.each do |cur|
update_stack(stack, cur)
end
if stack.size == 1
puts "Answer = #{stack.pop}"
else
puts "Bad number of arguments, try again!"
end
end
if ARGV.empty?
@interactive = true
interactive
else
@interactive = false
all_at_once ARGV
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment