marcamillion marcamillion - 1 year ago 81
Ruby Question

How do I detect if a CSV is empty or has no rows?

I have an array

, where I am reading each item and adding it to a CSV file like so:

info.each do |listing|, "a+") do |csv|
csv << listing

However, what I want to do is when the CSV is empty (i.e. this is the first row being added to this specific CSV) I will add a header first before adding any data. A header being a row that just has data-categories: First Name, Last Name, Address, etc.

If I add it to that loop, it will add it after each record.

Also, there is no guarantee that the first item in the array will be the first item in the CSV. The CSV could be empty by the time the iterator is at
for example.

How do I approach this?

Answer Source

You can check whether the CSV::Table contains any rows:

require 'csv'
filepath  = File.join('.', 'test')
csv       =, 'wb', col_sep: ';', quote_char: "\x00")
csv_table = CSV.table(filepath)
#=> 0