Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # The following code uses the the example on wikipedia:
- # http://en.wikipedia.org/wiki/Comma-separated_values
- # Program has been tested with ruby 1.8.7
- # I apologise for the Hungarian notation, but describing
- # the classes involved is appropriate for this example,
- # since it's about converting between different data structures.
- require "csv"
- require "yaml"
- # This is the example given in wikipedia
- cars_in_csv = "Year,Make,Model,Length
- 1997,Ford,E350,2.34
- 2000,Mercury,Cougar,2.38"
- # The parser just converts these into an array of CSV cells
- array_of_csv_cells = CSV.parse cars_in_csv
- # The first CVS row are the headings
- headings = array_of_csv_cells.shift.map {|heading| heading.to_s}
- # Convert the array of CSV cells into an Array of Hashes
- cars_in_ruby_structures = array_of_csv_cells.map do |cells|
- hsh = {}
- (cells.map {|cell| cell.to_s}).each_with_index do |cell_str, index|
- hsh[headings[index]] = cell_str
- end
- hsh
- end
- # Then you convert to yaml
- cars_in_yaml = cars_in_ruby_structures.to_yaml
- # So you can see what the yaml looks like
- puts cars_in_yaml
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement