Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.49 KB | None | 0 0
  1. class Calculator
  2. def initialize(*args)
  3. @num_ary = []; @oper_ary = []
  4. args.each do |arg|
  5. arg.is_a?(Numeric) ? @num_ary << arg : @oper_ary << arg
  6. end
  7. end
  8.  
  9. def calculate
  10. result = nil
  11. @oper_ary.each do |oper|
  12. num1 = result.nil? ? @num_ary.shift : result
  13. num2 = @num_ary.shift
  14. result = num1.send(oper, num2)
  15. end
  16. result
  17. end
  18. end
  19.  
  20. # Calculator.new(1, :+, 2, :*, 3, :/, 9, :-, 4).calculate
  21. # => -3
  22.  
  23. # Calculator.new(3, :**, 2, :%, 4).calculate
  24. # => 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement