Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created October 2, 2020 01:05
Show Gist options
  • Save komasaru/4775935f3dc2f110b26b3847668a4fb7 to your computer and use it in GitHub Desktop.
Save komasaru/4775935f3dc2f110b26b3847668a4fb7 to your computer and use it in GitHub Desktop.
Ruby script to calculate a formula expressed with RPN.
#! /usr/local/bin/ruby
#*********************************************************
# Ruby script to caculate a formula string by RPN.
#*********************************************************
class String
RE_0 = Regexp.new('[=\s]+$')
RE_1 = Regexp.new('\s+')
RE_D = Regexp.new('\d+')
RE_PL = Regexp.new('\+')
RE_MN = Regexp.new('\-')
RE_PR = Regexp.new('\*')
RE_DV = Regexp.new('\/')
def rpn
stack = []
self.sub(RE_0, "").split(RE_1).each do |t|
if t =~ RE_D
stack.push(t.to_f)
next
end
r, l = stack.pop, stack.pop
case t
when RE_PL; stack.push(l.to_f + r.to_f)
when RE_MN; stack.push(l.to_f - r.to_f)
when RE_PR; stack.push(l.to_f * r.to_f)
when RE_DV; stack.push(l.to_f / r.to_f)
end
end
return stack.pop
end
end
if __FILE__ == $0
f = $stdin.gets.chomp
exit if f == ""
puts f.rpn
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment