Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # using regular iteration
- #
- # the CSV::Reader.parse method loops through CSV data and returns an array of items for
- # each row of the file. We use File.open() to pass in a file that contains CSV data
- #
- i=0
- CSV::Reader.parse(File.open('data.csv','rb')) do |row|
- i += 1 # increment our line counter
- # we want to ignore the first line because it has headers
- if (i > 1)
- name = row[0]
- email = row[1]
- save_record(name,email)
- end
- end
- #
- # this works, but it's not re-usable. If we want to change the number of lines
- # to ignore when reading a different file, we have to repeat the whole code structure.
- # We also expose a utility variable "i" in our main code which makes things harder to read
- #
- # to parse another file
- i=0
- CSV::Reader.parse(File.open('report.csv','rb')) do |row|
- i += 1 # increment our line counter
- # we want to ignore the first 3 lines this time
- if (i > 3)
- date = row[0]
- first_month = row[1]
- total = row[2]
- # and so on...
- save_report(date,first_month,total)
- end
- end
Add Comment
Please, Sign In to add comment