csv_reading.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/local/bin/ruby -w
  2. # csv_reading.rb
  3. #
  4. # Created by James Edward Gray II on 2006-11-05.
  5. # Copyright 2006 Gray Productions. All rights reserved.
  6. require "faster_csv"
  7. CSV_FILE_PATH = File.join(File.dirname(__FILE__), "purchase.csv")
  8. CSV_STR = <<END_CSV
  9. first,last
  10. James,Gray
  11. Dana,Gray
  12. END_CSV
  13. # read a file line by line
  14. FasterCSV.foreach(CSV_FILE_PATH) do |line|
  15. puts line[1]
  16. end
  17. # >> Product Description
  18. # >> Text Editor
  19. # >> MacBook Pros
  20. # slurp file data
  21. data = FasterCSV.read(CSV_FILE_PATH)
  22. puts data.flatten.grep(/\A\d+\.\d+\Z/)
  23. # >> 25.00
  24. # >> 2499.00
  25. # read a string line by line
  26. FasterCSV.parse(CSV_STR) do |line|
  27. puts line[0]
  28. end
  29. # >> first
  30. # >> James
  31. # >> Dana
  32. # slurp string data
  33. data = FasterCSV.parse(CSV_STR)
  34. puts data[1..-1].map { |line| "#{line[0][0, 1].downcase}.#{line[1].downcase}" }
  35. # >> j.gray
  36. # >> d.gray
  37. # adding options to make data manipulation easy
  38. total = 0
  39. FasterCSV.foreach( CSV_FILE_PATH, :headers => true,
  40. :header_converters => :symbol,
  41. :converters => :numeric ) do |line|
  42. line_total = line[:quantity] * line[:price]
  43. total += line_total
  44. puts "%s: %.2f" % [line[:product_description], line_total]
  45. end
  46. puts "Total: %.2f" % total
  47. # >> Text Editor: 25.00
  48. # >> MacBook Pros: 4998.00
  49. # >> Total: 5023.00