Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
四則演算のパーサー(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
You can’t perform that action at this time.