Advertisement
VladikOtez

Ruby eval

Sep 11th, 2017
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.57 KB | None | 0 0
  1. def calc(expr)
  2.   res = 0
  3.   ary = expr.scan(/\d+|\D/).delete_if{|token| token == ' '}
  4.   stack = []
  5.   ary.each do |token|
  6.     if token.is_operator?
  7.      res += eval(stack.pop.to_i, token, stack.pop.to_i)
  8.     p stack.push(res)
  9.     else
  10.       stack.push(token)
  11.     end
  12.   end
  13.   stack.pop
  14. end
  15.  
  16. def eval(num1, operator, num2)
  17.   case operator
  18.     when '+'
  19.       num1 + num2
  20.     when '-'
  21.       num1 - num2
  22.     when '*'
  23.       num1 * num2
  24.     when '/'
  25.       num1.to_f / num2
  26.   end
  27. end
  28.  
  29.  
  30. class String
  31.   def is_operator?
  32.     %w(+ - / *).include?(self)
  33.   end
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement