Guest User

Untitled

a guest
Oct 17th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. # Parse a CSV file with column names.
  4. # The first line of the file is assumed
  5. # to be the column names, and also defines
  6. # the number of columns. Returns an
  7. # array of hashes.
  8. def csv(file)
  9. File.open(file) do|f|
  10. columns = f.readline.chomp.split(',')
  11.  
  12. table = []
  13. until f.eof?
  14. row = f.readline.chomp.split(',')
  15. row = columns.zip(row).flatten
  16. table << Hash[*row]
  17. end
  18.  
  19. return columns, table
  20. end
  21. end
  22.  
  23. # Print a grade book from a CSV file.
  24. # A grade book is alphabetized by first
  25. # and last name and the columns are
  26. # aligned properly.
  27. columns, grades = csv(ARGV[0])
  28.  
  29. # Sort names by last name, then first name
  30. grades.sort! do|a,b|
  31. a['Name'].split(' ').reverse.join(' ') <=> b['Name'].split(' ').reverse.join(' ')
  32. end
  33.  
  34. # Determine column widths
  35. column_widths = {}
  36. columns.each do|c|
  37. column_widths[c] = [ c.length, *grades.map{|g| g[c].length } ].max
  38. end
  39.  
  40. # Make the format string
  41. format = columns.map{|c| "%-#{column_widths[c]}s" }.join(' | ')
  42.  
  43. # Print the table
  44. puts format % columns
  45. puts format.tr(' |', '-+') % column_widths.values.map{|v| '-'*v }
  46.  
  47. grades.each do|g|
  48. puts format % columns.map{|c| g[c] }
  49. end
Add Comment
Please, Sign In to add comment