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

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

class CSV::Reader
	def to_table
		struct = Array.struct { |v| v.downcase.gsub(/\s/, '_').to_sym } { |row| row }
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>