From: James Gray Date: 2008-09-02T21:13:32+09:00 Subject: Re: Parsing a CSV file column-wise On Sep 2, 2008, at 3:59 AM, Chris Lowis wrote: > On Sep 2, 8:34 am, Lars Broecker > wrote: >> Chris Lowis schrieb: >> >> >> >>> Is there a short-cut to parsing a CSV file column-wise using any of >>> the available Ruby CSV libraries ? >> >>> For example, at the moment I have: >> >>> require 'csv' >>> data = "1,2,3\n4,5,6\n7,8,9" >>> CSV::parse(data) # => [["1", "2", "3"], ["4", "5", "6"], ["7", >>> "8", >>> "9"]] >> > Lars, > > That's great ! To summarise for anyone else looking for an answer : > > Given a CSV file tmp.csv > > one,two,three > 1,2,3 > 4,5,6 > 7,8,9 > > Where the first row contains the column headers > > require 'fastercsv' > table = FasterCSV::table('./tmp.csv') > > table.by_col[2] # => [3, 6, 9] Or you could access them by name: #!/usr/bin/env ruby -wKU require "rubygems" require "faster_csv" csv = FCSV.parse(< true, :header_converters => :symbol) one,two,three 1,2,3 4,5,6 7,8,9 END_DATA csv[:two] # => ["2", "5", "8"] __END__ James Edward Gray II