How to use fastercsv to get rows as hashes?

Hi - I’m fairly new to ruby and trying to read a csv file using the
fastercsv gem. I managed to read the rows arrays of data using:

require ‘fastercsv’

def read_csv
path_to_file = “/home/work/some_file.csv”

open the csv file to read

csv = FasterCSV.open(path_to_file, “r”)

do stuff on rows as arrays

while row = csv.readline
#… row will be [“cell1”, “cell2”, “cell3”, …]
end
end

What I’m trying to understand is how do I get the row as a hash where
the keys are the column headers (so I don’t have to remember where each
column sits in the array):

#…inside loop
col1 = row[‘some column’]
col2 = row[‘another column’]
#…

I’m sure there’s a way to do this, but the RDoc wasn’t much help. I’d
appreciate any tips - thanks!

On Nov 20, 2008, at 6:38 AM, sa 125 wrote:

Hi - I’m fairly new to ruby

Hello and welcome.

do stuff on rows as arrays

while row = csv.readline
#… row will be [“cell1”, “cell2”, “cell3”, …]
end
end

Looking good. You can simplify it a bit if you like though:

def read_csv(path = “/home/work/some_file.csv”)
FCSV.foreach(path) do |row|
# …
end
end

foreach() is just a shortcut for open() and each(), which works like
your while loop.

What I’m trying to understand is how do I get the row as a hash where
the keys are the column headers (so I don’t have to remember where
each
column sits in the array):

#…inside loop
col1 = row[‘some column’]
col2 = row[‘another column’]
#…

The first step is to tell FasterCSV that the file has headers. You
can do that by changing this line:

 FCSV.foreach(path) do |row|

to this:

 FCSV.foreach(path, :headers => true) do |row|

When you make that change, row will become a FasterCSV::Row object,
instead of a normal Array. It has many features and will allow you to
access columns by name exactly as you show above. If you really do
want a Hash though, you can get it with a simple method call:

row_hash = row.to_hash

Hope that helps.

James Edward G. II

That’s exactly what I needed - many thanks!