I have some code that reads a file into an array of lines, and then parses those lines to get at the structured data. The input file has various different data types that need to be handled differently, additionally there are major sections for various accounts (mobile numbers).
I loop through the lines looking for the account line, identify the account, and then I want to use that account until I encounter the next account line. The lines in between potentially represent various types of data belonging to that account. The problem is, after I find the account line and set a local variable (cur_num), the variable is set to nil when I want to use it. Why, how is this happening? I am learning Ruby so I want more than a fix - I want to understand why it works this way.
Here is my code:
count = 0
cur_num = ""
lines.each do |line|
unless (line.strip.eql?("")) # edited due to comment from normalocity
if (line.slice(0,15) == "Mobile Number:,")
cur_num = line.slice(15,12)
count = 1
puts "Current Number: #{cur_num}"
#puts "Object Type: #{cur_num.class}"
else
data = line.strip.split(',')
if (data.length > 8)
data.unshift(cur_num)
#if (count.modulo(10) == 0 || count == 1)
puts "[#{cur_num}] #{data.inspect}"
#pp data
#end
count += 1
end
end
end
end
An overview of the input data structure would look like this:
Account 1
Data Section A
data line 1
data line 2
Data Section B
data line 1
data line 2
Account 2
Data Section A
data line 1
data line 2
Data Section B
data line 1
data line 2
end
adding code to duplicate lines array you should paste this above code sample if you are attempting to duplicate. I'm putting it here at the end to try to make my question more readable:
lines = []
lines.push("ATT Wireless Bill")
lines.push("")
lines.push("Mobile Number:,770-555-1212")
lines.push("item,date,time,number called,rate period,plan type,minutes,airtime charge,ld charge,total charge")
lines.push("")
lines.push("1,2011-01-02,6:56AM,404-555-1212,NW,UNW,4,0.00,0.00,0.00")
lines.push("")
lines.push("2,2011-01-03,6:56AM,404-555-1212,NW,UNW,4,0.00,0.00,0.00")
lines.push("")
lines.push("1,2011-01-03,7:56AM,404-555-1213,DT,UM2M,5,0.00,0.00,0.00")
lines.push("")
lines.push("Mobile Number:,770-555-1213")
lines.push("item,date,time,number called,rate period,plan type,minutes,airtime charge,ld charge,total charge")
lines.push("")
lines.push("1,2011-01-02,6:56AM,404-555-1212,NW,UNW,4,0.00,0.00,0.00")
lines.push("")
lines.push("2,2011-01-03,6:56AM,404-555-1212,NW,UNW,4,0.00,0.00,0.00")
lines.push("")
lines.push("1,2011-01-03,7:56AM,404-555-1213,DT,UM2M,5,0.00,0.00,0.00")
lines.push("")