Here is an example of symbolic syntax using Ruby 1.9. In the examples below, the code reads a CSV file named data.csv from the Rails db directory.
:headers => true treats the first row as a header instead of a data row. :header_converters => :symbolize then converts each cell in the title bar to a Ruby symbol.
CSV.foreach("#{Rails.root}/db/data.csv", {:headers => true, :header_converters => :symbol}) do |row| puts "#{row[:foo]},#{row[:bar]},#{row[:baz]}" end
In Ruby 1.8:
require 'fastercsv' CSV.foreach("#{Rails.root}/db/data.csv", {:headers => true, :header_converters => :symbol}) do |row| puts "#{row[:foo]},#{row[:bar]},#{row[:baz]}" end
Based on the CSV provided by Poul (StackOverflow questionnaire), the output from the above code example will be:
1,2,3 blah,7,blam 4,5,6
Depending on the characters used in the headers of the CSV file, headers may need to be displayed to see how the CSV (FasterCSV) converts the line headers to characters. You can output an array of headers from CSV.foreach .
row.headers
scarver2 Jan 28 2018-12-18T00: 00Z
source share