-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathparsing.rb
More file actions
58 lines (47 loc) · 812 Bytes
/
parsing.rb
File metadata and controls
58 lines (47 loc) · 812 Bytes
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
class Parser
attr_reader :tags
def initialize(str)
@buffer = StringScanner.new(str)
@tags = []
parse
end
def parse
until @buffer.eos?
skip_spaces
parse_element
end
end
def parse_element
if @buffer.peek(1) == '<'
@tags << find_tag
last_tag.content = find_content
end
end
def skip_spaces
@buffer.skip(/\s+/)
end
def find_tag
@buffer.getch
tag = @buffer.scan(/\w+/)
@buffer.getch
Tag.new(tag)
end
def find_content
tag = last_tag.name
content = @buffer.scan_until /<\/#{tag}>/
content.sub("</#{tag}>", "")
end
def first_tag
@tags.first
end
def last_tag
@tags.last
end
end
class Tag
attr_reader :name
attr_accessor :content
def initialize(name)
@name = name
end
end