Created
May 20, 2009 15:01
-
-
Save dimiro1/114858 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# -*- coding: utf-8 -*- | |
class Stack < Array | |
end | |
class Calculator | |
def initialize | |
@stack = Stack.new | |
end | |
def eval(expr) | |
expr.each_char do |e| | |
case e | |
when " ": # nada | |
when "\n": # nada | |
when "\t": # nada | |
when "+": @stack.push(@stack.pop + @stack.pop) | |
when "-": @stack.push(@stack.pop + @stack.pop) | |
when "*": @stack.push(@stack.pop * @stack.pop) | |
when "#": @stack.push(Math.sqrt(@stack.pop)) | |
when "^": | |
first = @stack.pop | |
@stack.push(@stack.pop ** first) | |
when "/": | |
first = @stack.pop | |
if first == 0 | |
puts "Não pode dividir por zero" | |
exit(1) | |
else | |
@stack.push(first * @stack.pop) | |
end | |
else | |
@stack.push(e.to_f) | |
end | |
end | |
return @stack.pop | |
end | |
def print_terminal | |
print ">> " | |
end | |
def read | |
gets | |
end | |
def loop_read_eval | |
loop do | |
print_terminal | |
puts eval(read) | |
end | |
end | |
end | |
c = Calculator.new | |
c.loop_read_eval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment