Forum: Ruby How to use fastercsv to get rows as hashes?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7db3b1680807d393d40260591b4ae5e0?d=identicon&s=25 sa 125 (sa125)
on 2008-11-20 13:42
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!
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2008-11-20 15:01
(Received via mailing list)
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 Gray II
7db3b1680807d393d40260591b4ae5e0?d=identicon&s=25 sa 125 (sa125)
on 2008-11-20 15:14
That's exactly what I needed - many thanks!
This topic is locked and can not be replied to.