csv_table.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/local/bin/ruby -w
  2. # csv_table.rb
  3. #
  4. # Created by James Edward Gray II on 2006-11-04.
  5. # Copyright 2006 Gray Productions. All rights reserved.
  6. #
  7. # Feature implementation and example code by Ara.T.Howard.
  8. require "faster_csv"
  9. table = FCSV.parse(DATA, :headers => true, :header_converters => :symbol)
  10. # row access
  11. table[0].class # => FasterCSV::Row
  12. table[0].fields # => ["zaphod", "beeblebrox", "42"]
  13. # column access
  14. table[:first_name] # => ["zaphod", "ara"]
  15. # cell access
  16. table[1][0] # => "ara"
  17. table[1][:first_name] # => "ara"
  18. table[:first_name][1] # => "ara"
  19. # manipulation
  20. table << %w[james gray 30]
  21. table[-1].fields # => ["james", "gray", "30"]
  22. table[:type] = "name"
  23. table[:type] # => ["name", "name", "name"]
  24. table[:ssn] = %w[123-456-7890 098-765-4321]
  25. table[:ssn] # => ["123-456-7890", "098-765-4321", nil]
  26. # iteration
  27. table.each do |row|
  28. # ...
  29. end
  30. table.by_col!
  31. table.each do |col_name, col_values|
  32. # ...
  33. end
  34. # output
  35. puts table
  36. # >> first_name,last_name,age,type,ssn
  37. # >> zaphod,beeblebrox,42,name,123-456-7890
  38. # >> ara,howard,34,name,098-765-4321
  39. # >> james,gray,30,name,
  40. __END__
  41. first_name,last_name,age
  42. zaphod,beeblebrox,42
  43. ara,howard,34