-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.rb
46 lines (39 loc) · 892 Bytes
/
calculator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Calculator
UnrecognizedInputError = Class.new(StandardError)
MATCHERS = {
integer: /^-?\d+$/,
float: /^-?[0-9]+(\.[0-9]+)?$/,
operator: /^[-+\/*]$/
}.freeze
attr_reader :stack
def initialize
@stack = []
end
def handle_input(input)
[].tap do |output|
input.to_s.split(' ').each do |part|
handle_part(part, output)
end
end
end
private
def handle_part(part, output)
case part
when MATCHERS[:integer]
@stack.push(part.to_i)
when MATCHERS[:float]
@stack.push(part.to_f)
when MATCHERS[:operator]
output.push(operate(part))
when /^state$/ # state command, just inspect the stack
output.push(@stack.inspect)
else
raise UnrecognizedInputError.new
end
end
def operate(operator)
result = @stack.reduce(operator.to_sym)
@stack = []
result
end
end