Guest User

Untitled

a guest
Jan 24th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. class Csv
  2. def self.parse(handle, args={})
  3. # read a csv creating a hash with the first column as the primary identifier
  4. # assumes that the first line of the csv file is the header
  5. # uses header names as keys for the values for each primary identifier
  6.  
  7. sep = args[:sep] || ',' # record separator
  8. key = args[:key] || 0 # which column is the key?
  9.  
  10. # TODO: add support for taking a Proc as an argument for key
  11.  
  12. # data is stored as a simple hash
  13. data = Hash.new
  14.  
  15. # parse header
  16. header = handle.gets.strip.split(sep)
  17. header.delete_at(key)
  18.  
  19. # read data
  20. handle.each do |line|
  21. line = line.strip.split(sep)
  22. datum = Hash.new
  23. primary = line.delete_at key
  24. header.zip(line).each do |k, d|
  25. if datum.has_key? k
  26. raise "Duplicate secondary key: #{k}! in #{handle.path}"
  27. end
  28. datum[k] = d
  29. end
  30. if data.has_key? primary
  31. raise "Duplicate primary key: #{primary}! in #{handle.path}"
  32. end
  33. data[primary] = datum
  34. end
  35.  
  36. # return data as a simple Hash
  37. data
  38. end
  39.  
  40. end
Add Comment
Please, Sign In to add comment