Monthly Archives: January 2012

Cloud County 765

Cloud County 765

Photo by Jake on the AARoads Blog.

My clock. It ticks.

201_0291.MOV, originally uploaded by metrixcreate.

My clock. It ticks.

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 }