-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenizer.rb
More file actions
57 lines (48 loc) · 1.08 KB
/
tokenizer.rb
File metadata and controls
57 lines (48 loc) · 1.08 KB
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
class String
def number?
match(/[0-9]/)
end
end
class Tokenizer
attr_accessor :source, :index
def initialize(source, index)
@source = source
@index = index
end
def call
puts @source
end
def peek
@index < @source.length {-1} ? @source[@index+1] : ''
end
def tokenize
@index = 0
tokens = []
while @index < @source.length
c = @source[@index]
next if c.empty?
r = case c
when '(' then {type: :LPAREN}
when ')' then {type: :RPAREN}
when '+' then {type: :OPERATOR, val: c}
when '*' then {type: :OPERATOR, val: c}
when '-' then {type: :OPERATOR, val: c}
when '/' then {type: :OPERATOR, val: c}
else {type: :UNKNOWN}
end
tokens.push r unless r[:type] == :UNKNOWN
if c.number?
str = c
next_char = peek
while @index < @source.length and next_char.number? do
@index+=1
str += next_char
next_char = peek
end
tokens.push({type: :NUMBER, val: str.to_i})
end
@index+=1
end
tokens
end
end