Advertisement
Guest User

CSV to YAML example

a guest
Jan 11th, 2011
544
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.08 KB | None | 0 0
  1. # The following code uses the the example on wikipedia:
  2. # http://en.wikipedia.org/wiki/Comma-separated_values
  3. # Program has been tested with ruby 1.8.7
  4. # I apologise for the Hungarian notation, but describing
  5. # the classes involved is appropriate for this example,
  6. # since it's about converting between different data structures.
  7.  
  8. require "csv"
  9. require "yaml"
  10.  
  11. # This is the example given in wikipedia
  12. cars_in_csv = "Year,Make,Model,Length
  13. 1997,Ford,E350,2.34
  14. 2000,Mercury,Cougar,2.38"
  15.  
  16. # The parser just converts these into an array of CSV cells
  17. array_of_csv_cells = CSV.parse cars_in_csv
  18.  
  19. # The first CVS row are the headings
  20. headings = array_of_csv_cells.shift.map {|heading| heading.to_s}
  21.  
  22. # Convert the array of CSV cells into an Array of Hashes
  23. cars_in_ruby_structures = array_of_csv_cells.map do |cells|
  24.     hsh = {}
  25.     (cells.map {|cell| cell.to_s}).each_with_index do |cell_str, index|
  26.         hsh[headings[index]] = cell_str
  27.     end
  28.     hsh
  29. end
  30.  
  31. # Then you convert to yaml
  32. cars_in_yaml = cars_in_ruby_structures.to_yaml
  33.  
  34. # So you can see what the yaml looks like
  35. puts cars_in_yaml
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement