CSV file reading in ruby 1.9 (fastercsv)
Fastercsv, which is the default in ruby 1.9, uses a hash for specifying the column separator.
Here, we read a tab delimited file and push each row into an array. We also print the first 2 columns.
require ‘csv’
ctr = 0
@data = []
CSV.foreach(@file,:col_sep => “\t”) do |row|
@data << row
puts ” #{row[0]} | #{row[1]} ” #unless row[1] =~ /^\[x\]/
ctr += 1
end
puts ” #{ctr} rows “
To see the other options, do ri CSV::new
in a Terminal. Some options are row_sep, field_size_limit, converters, headers (:first_row means the first row is treated as a header, if set to array then the array is used as a header), skip_blanks (true), force_quotes (true), write_headers (true), and a few others.
—
# git patching
URL
— Nick Quaranto
Dude, that’s nothing. I used to work across the hall from Linus Torvalds, and he used to pull down his pants and shake his balls at passers-by through his office window.
— barfolomew
[…] CSV file reading in ruby 1.9 (fastercsv) May 2010 […]
2010 in review « The Accidental Rubyist
January 2, 2011 at 10:55 am