-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.rb
66 lines (58 loc) · 1.55 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Calculator
@state = :in # :in, :out, :first_in_and_mem
@has_memory = false
@formats = []
@values = []
@mem_values = []
def initialize(formats)
@formats = formats
raise "The first format item must be :t" if ( @formats[0] != :t)
if ( @formats & [:d] ).size == 0
@has_memory = false
@state = :in
else
@has_memory = true
@state = :first_in
end
end
def in(values)
case @state
when :out
raise "Now is not time to a in. Is out time."
when :in
@state = :out
if @has_memory
@mem_values = @values
end
@values = values
when :first_in
@state = :in
@values = values
end
end
def out()
values = []
case @state
when :in
raise "The program is waiting to in."
when :first_in
raise "The program is waiting to second in."
end
values = @values.dup
@formats.each_with_index { |f, i|
if @has_memory
case f
when :d
values[i] -= @mem_values[i]
when :v
values[i] = (values[i] - @mem_values[i]) / (values[0] - @mem_values[0])
end
end
if (values[i].is_a? (Float))
values[i] = "%.2f".%(values[i]).to_f
end
}
@state = :in
values
end
end