Skip to content

Instantly share code, notes, and snippets.

@tejasbubane
Last active January 1, 2016 07:09
Show Gist options
  • Save tejasbubane/8109946 to your computer and use it in GitHub Desktop.
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
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