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):
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):
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: