Skip to content

Instantly share code, notes, and snippets.

@dimiro1
Created May 20, 2009 15:01
Show Gist options
  • Save dimiro1/114858 to your computer and use it in GitHub Desktop.
Save dimiro1/114858 to your computer and use it in GitHub Desktop.
# -*- 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