Skip to content

Instantly share code, notes, and snippets.

@eric1234
Created September 10, 2009 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eric1234/184784 to your computer and use it in GitHub Desktop.
Save eric1234/184784 to your computer and use it in GitHub Desktop.
CSV::Reader extension: Utilize header row
# Extends CSV::Reader to assume the first row is the headers to the data
# (i.e. fields names). Each non-header row in the data with then be
# passed a hash instead of the normal array so you can reference the
# data by field name. For example:
#
# CSV::Reader::WithHeader.parse(io) do |row|
# puts row['first_name'] + ' ' + row['last_name']
# end
class CSV::Reader::WithHeader < CSV::Reader
def self.parse(str_or_readable, fs=',', &blk)
headers = nil
super str_or_readable, fs do |row|
if headers
blk.call Hash[*headers.zip(row).flatten]
else
headers = row
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment