Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def calc(expr)
- res = 0
- ary = expr.scan(/\d+|\D/).delete_if{|token| token == ' '}
- stack = []
- ary.each do |token|
- if token.is_operator?
- res += eval(stack.pop.to_i, token, stack.pop.to_i)
- p stack.push(res)
- else
- stack.push(token)
- end
- end
- stack.pop
- end
- def eval(num1, operator, num2)
- case operator
- when '+'
- num1 + num2
- when '-'
- num1 - num2
- when '*'
- num1 * num2
- when '/'
- num1.to_f / num2
- end
- end
- class String
- def is_operator?
- %w(+ - / *).include?(self)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement