Skip to content

Instantly share code, notes, and snippets.

@ser1zw
Created December 6, 2018 09:29
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 ser1zw/98b0512106fb24a3a84ec255ce0d3a07 to your computer and use it in GitHub Desktop.
Save ser1zw/98b0512106fb24a3a84ec255ce0d3a07 to your computer and use it in GitHub Desktop.
逆ポーランド記法の練習
require 'set'
class RPN
def initialize(exp)
@exp = exp.split(/\s+/)
@stack = []
@operators = Set['+', '-', '*', '/', '%'].freeze
end
def eval
while v = @exp.shift
if @operators.include? v
n2, n1 = @stack.pop, @stack.pop
@stack << n1.send(v.to_sym, n2)
else
@stack << v.to_i
end
end
@stack.last
end
end
DATA.read.lines.map(&:chomp).each { |exp|
puts "(#{exp}) = #{RPN.new(exp).eval}"
}
__END__
3 4 +
3 4 + 1 2 - *
1 5 + 2 3 + *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment