tags:

views:

25

answers:

1

I would like to parse a CSV file so that each row is treated like an object with the header-row being the names of the attributes in the object. I could write this, but I'm sure its already out there.

Here is my csv
"foo","bar","baz"
1,2,3
"blah",7,"blam"
4,5,6

So the code would look something like this.

CSV.open('my_file.csv','r') do |csv_obj|
  puts csv_obj.foo   #prints 1 the 1st time, "blah" 2nd time, etc
  puts csv.bar       #prints 2 the first time, 7 the 2nd time, etc
end

With Ruby's CSV module I believe I can only access the fields by index. I think the above code would be a bit more readable. Any ideas? Thanks!

+2  A: 

To the best of my knowledge CSV (and FasterCSV) only parse the CSV into an Array or Hash. Using FasterCSV you can get a hash back instead of a Array like this

FasterCSV.foreach('my_file.csv', :headers => true) do |csv_obj|

  puts csv_obj['foo'] #prints 1 the 1st time, "blah" 2nd time, etc

  puts csv_obj['bar'] #prints 2 the first time, 7 the 2nd time, etc

end

Its not dot syntax but it is much nicer to work with than numeric indexes.

As an aside, for Ruby 1.8.x FasterCSV is a much faster implementation of the CSV parser than the built in CSV class. So much so that Ruby 1.9 replaced the stdlib version of CSV with FasterCSV.

Peer

Peer Allan