Created
October 2, 2020 01:05
-
-
Save komasaru/4775935f3dc2f110b26b3847668a4fb7 to your computer and use it in GitHub Desktop.
Ruby script to calculate a formula expressed with RPN.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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