Guest User

Untitled

a guest
Apr 23rd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. #
  2. # using regular iteration
  3. #
  4. # the CSV::Reader.parse method loops through CSV data and returns an array of items for
  5. # each row of the file. We use File.open() to pass in a file that contains CSV data
  6. #
  7. i=0
  8. CSV::Reader.parse(File.open('data.csv','rb')) do |row|
  9. i += 1 # increment our line counter
  10.  
  11. # we want to ignore the first line because it has headers
  12. if (i > 1)
  13.  
  14. name = row[0]
  15. email = row[1]
  16. save_record(name,email)
  17.  
  18. end
  19. end
  20.  
  21. #
  22. # this works, but it's not re-usable. If we want to change the number of lines
  23. # to ignore when reading a different file, we have to repeat the whole code structure.
  24. # We also expose a utility variable "i" in our main code which makes things harder to read
  25. #
  26.  
  27. # to parse another file
  28. i=0
  29. CSV::Reader.parse(File.open('report.csv','rb')) do |row|
  30. i += 1 # increment our line counter
  31.  
  32. # we want to ignore the first 3 lines this time
  33. if (i > 3)
  34.  
  35. date = row[0]
  36. first_month = row[1]
  37. total = row[2]
  38. # and so on...
  39. save_report(date,first_month,total)
  40.  
  41. end
  42. end
Add Comment
Please, Sign In to add comment