Output array to CSV in Ruby
To a file:
require 'csv'CSV.open("myfile.csv", "w") do |csv| csv << ["row", "of", "CSV", "data"] csv << ["another", "row"] # ...end
To a string:
require 'csv'csv_string = CSV.generate do |csv| csv << ["row", "of", "CSV", "data"] csv << ["another", "row"] # ...end
Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html
I've got this down to just one line.
rows = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ... ]csv_str = rows.inject([]) { |csv, row| csv << CSV.generate_line(row) }.join("")#=> "a1,a2,a3\nb1,b2,b3\nc1,c2,c3\n"
Do all of the above and save to a csv, in one line.
File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row| csv << CSV.generate_line(row) }.join(""))}
NOTE:
To convert an active record database to csv would be something like this I think
CSV.open(fn, 'w') do |csv| csv << Model.column_names Model.where(query).each do |m| csv << m.attributes.values endend
Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:
rowid = 0CSV.open(fn, 'w') do |csv| hsh_ary.each do |hsh| rowid += 1 if rowid == 1 csv << hsh.keys# adding header row (column labels) else csv << hsh.values end# of if/else inside hsh end# of hsh's (rows)end# of csv open
If your data isn't structured this obviously won't work