-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.rb
More file actions
109 lines (99 loc) · 2.46 KB
/
parser.rb
File metadata and controls
109 lines (99 loc) · 2.46 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# read data in string
class CSVParser
attr_reader :data, :current_row, :current_field, :position, :in_quotes,
:field_delimiter, :quote_delimiter, :string
def initialize(string, field_delimiter = ',', quote_delimiter = '"')
@data = []
@current_row = []
@current_field = ""
@string = string
@position = 0
@in_quotes = false
@field_delimiter = field_delimiter
@quote_delimiter = quote_delimiter
end
def parse
while position < string.length
consume_character
end
current_row << current_field unless current_field.empty?
data << current_row unless current_row.empty?
data
end
private
def consume_character
t = string[position]
if t == quote_delimiter
consume_quote
elsif !in_quotes && t == field_delimiter
current_row << current_field
@current_field = ""
elsif !in_quotes && t == "\n"
current_row << current_field
data << current_row
puts current_row.inspect
@current_row = []
@current_field = ''
else
current_field << t
end
@position += 1
end
def consume_quote
if in_quotes
next_character = string[position + 1] rescue ''
if next_character == quote_delimiter
current_field << quote_delimiter
@position += 1
else
@in_quotes = false
end
else
@in_quotes = true
end
end
end
# def csv_parser(string,field_delimiter,quote_delimiter)
#
# data = []
# current_row = []
# current_field = ""
# i = 0
# in_quotes = false
#
# while i < string.length
# t = string[i]
# if t == quote_delimiter
# if in_quotes
# next_character = string[i + 1] rescue ''
# if next_character == quote_delimiter
# current_field << quote_delimiter
# i += 1
# else
# in_quotes = false
# end
# else
# in_quotes = true
# end
# elsif !in_quotes && t == field_delimiter
# current_row << current_field
# current_field = ""
# elsif !in_quotes && t == "\n"
# current_row << current_field
# data << current_row
# puts current_row.inspect
# current_row = []
# current_field = ''
# else
# current_field << t
# end
# i = i + 1
# end
#
# current_row << current_field unless current_field.empty?
# data << current_row unless current_row.empty?
#
# data
# end
csv_data = File.read("cars.csv") ; csv_data.length
puts CSVParser.new(csv_data).parse.inspect