Last active
January 1, 2016 07:09
-
-
Save tejasbubane/8109946 to your computer and use it in GitHub Desktop.
Convert a csv file to array of hashes (just like SmarterCSV), useful when SmarterCSV throws wierd errors
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
require 'csv' | |
def csv_to_array(file_location) | |
csv = CSV::parse(File.open(file_location, 'r') {|f| f.read }) | |
fields = csv.shift | |
fields = fields.map {|f| f.downcase.gsub(" ", "_").to_sym} | |
csv.collect { |record| Hash[*fields.zip(record).flatten ] } | |
end | |
test = csv_to_array('test.csv') | |
# thanks to => http://darrenknewton.com/2010/09/05/convert-csv-to-text-with-ruby/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment