Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Struct "magic" - creating objects from CSV file (See related posts)


require 'csv'

csv = CSV.open('some_file.csv', 'r')
Post = Struct.new(*(csv.shift.map { |f| f.to_sym })) # Nice! Read in CSV header, turns them into symbols, and creates a new Struct.
posts = csv.inject([]) do |posts, row|
  posts << Post[*row]
end
csv.close

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts