Treating CSV files like tables in Ruby

Want to do some quick-and-dirty work in irb on data in CSV format? With the arrayfields gem, you can access array fields by name. I’ve mixed in some code to the CSV library to use the header row to provide fields for arrayfields, e.g.:

employees.csv
1 id First Name Last Name Username
2 1 Andrew Filer afiler
3 2 Ulysses Sername username
irb> require "csvtables"
irb> t = CSV::table('employees.csv')
irb> t.first.last_name
=> "Filer"

The code:

require 'arrayfields'
require 'csv'

class CSV
	def self.table(filename, mode='r')
		open(filename, mode).to_table
	end
end

class CSV::Reader
	def to_table
		struct = Array.struct self.first.map { |v| v.downcase.gsub(/\s/, '_').to_sym }
		self.map { |row| struct.new row }
	end
end
This entry was posted in Code. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>