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.

3
  • @sanfor but I guess my question is a bit different because mine includes to generate new columns. Commented Aug 27, 2015 at 5: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"]] Commented Aug 27, 2015 at 5:53
  • @gagangami corrected Commented Aug 27, 2015 at 5:55

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.