Skip to content

Instantly share code, notes, and snippets.

@obelisk68
Last active May 27, 2019 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obelisk68/7e0eaf56eb4ff16ac2aa7db28426e287 to your computer and use it in GitHub Desktop.
Save obelisk68/7e0eaf56eb4ff16ac2aa7db28426e287 to your computer and use it in GitHub Desktop.
四則演算のパーサー(Ruby)
def parse(text)
splited = text.scan(/[0-9\.]+|\+|\-|\*|\/|\(|\)|=/)
output = []
stack = []
a = nil
until (token = splited.shift) == "="
case token
when "(" then stack << token
when ")"
output << a until (a = stack.pop) == "("
when "*", "/"
loop do
a = stack.last
break unless %w(* /).include?(a)
output << stack.pop
end
stack << token
when "+", "-"
loop do
a = stack.last
break unless %w(+ - * /).include?(a)
output << stack.pop
end
stack << token
else
output << token
end
end
output << a while (a = stack.pop)
return output
end
def calculate(parsed)
stack = []
while (x = parsed.shift)
if %w(+ - * /).include?(x)
a, b = stack.pop, stack.pop
stack << eval("#{b} #{x} #{a}")
else
stack << x
end
end
stack.first
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment