0

Given array:

a = [[111,"Tue, 30 Jun 2015 23:50:55 KST +09:00"],[123,"Tue, 30 Jun 2015 23:50:55 KST +09:00"]]

And I want to convert this array to a new CSV file WITH NEW COLUMNS which would look like:

user_id | created_at
--------------------
111     | Tue, 30 Jun 2015 23:50:55 KST +09:00
123     | Tue, 30 Jun 2015 23:50:55 KST +09:00

How can I do this in Ruby? Thanks in advance.

ZHH
  • 99
  • 1
  • 10
  • @sanfor but I guess my question is a bit different because mine includes to generate new columns. – ZHH Aug 27 '15 at 05:53
  • 1
    provided array is not valid. it should be like this `a = [[111,"Tue, 30 Jun 2015 23:50:55 KST +09:00"],[123,"Tue, 30 Jun 2015 23:50:55 KST +09:00"]]` – Gagan Gami Aug 27 '15 at 05:53
  • @gagangami corrected – ZHH Aug 27 '15 at 05:55

3 Answers3

2

I managed to do this with(2nd edit) proper indentation

headers = ["user_id", "created_at"]
CSV.open("myfile.csv", "w", :col_sep => "\t| ", :headers => true) do |csv|
  csv << headers
  csv << ["-"*(headers.join.length+4*headers.length)] #Header separator in the length of header columns + tabs
  a.each {|row| csv << row } #Adding rows for each element of a
end
0e1val
  • 481
  • 3
  • 6
0
def export
  array = [[111,"Tue, 30 Jun 2015 23:50:55 KST +09:00"],[123,"Tue, 30 Jun 2015 23:50:55 KST +09:00"]]

  csv_data = CSV.generate do |csv|
   csv << [ "id","created_at"]
   array.each do |array|
     csv << [array[0],array[1]]
   end 
  end 
  send_data(csv_data, :type => 'text/csv', :filename => 'data.csv')
end
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
Dnyanarth lonkar
  • 869
  • 7
  • 12
0

Make method in model, i hope this will work for you. Tested from me. Working as you want.

CSV.generate(option) do |csv|
  csv << ['user_id', 'created_at']
    [[111,"Tue, 30 Jun 2015 23:50:55 KST +09:00"],[123,"Tue, 30 Jun 2015 23:50:55 KST +09:00"]].each do |array|
      csv << array
  end
end
Sajjad Murtaza
  • 1,444
  • 2
  • 16
  • 26