Created
September 10, 2009 20:08
-
-
Save eric1234/184784 to your computer and use it in GitHub Desktop.
CSV::Reader extension: Utilize header row
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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