-
Notifications
You must be signed in to change notification settings - Fork 12
/
stack.rb
86 lines (69 loc) · 1.47 KB
/
stack.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require_relative './BrainFlakError.rb'
class Stack
def initialize(name)
@name = name
@data = []
end
attr_reader :data
def pop
if @data.length != 0 then
return @data.pop
else
return 0
end
end
def push(current_value)
@data.push(current_value)
end
def peek
return @data.last || 0
end
def print_stack(ascii_mode, reverse)
(reverse ? @data: @data.reverse).each do |value|
if ascii_mode
begin
print (value % 2 ** 32).chr(Encoding::UTF_8)
rescue RangeError => ex
#Error at character -1 signals to the main level to insert the current location because stack doesn't know
#where we are in the execution. -1 cannot be attained any other way.
raise BrainFlakError.new("Value #{value} is out of range for UTF_8 encoding.",-1)
end
else
print value.to_s + "\n"
end
end
print "\n" if ascii_mode
STDOUT.flush
end
def talk
puts @name
end
def inspect_array
return @data.inspect
end
def char_inspect_array(n)
return @data.map {|a| (a%n).chr(Encoding::UTF_8)}.join("")
end
def height
return @data.length
end
def at(index)
return @data.at(index)
end
def get_data
return @data
end
def set_data(data)
@data = data
end
end
def is_opening_bracket?(b)
if b != nil then
return '([{<'.include? b
end
end
def is_closing_bracket?(b)
if b != nil then
return ')]}>'.include? b
end
end