0

I'm looking to pass an array into a csv as a single row. The code below showcases what I'm currently trying. The array is variable in length and will showcase something like this.

a = ["website url", "page link", "page link", "page link"]

The code essentially goes to a page using open-uri and scrapes out the links of each page. This is used for internal validation and checked against what we are expecting. If the link matches what we expect it is reported into the csv as a page link variable shown above.

I've currently tried using to_csv to format the data but inside the csv everything is in a single row including my comma separations.

def dwrite (array)
    CSV.open("filename.csv", "ab") do |csv|
            data = array.to_csv(row_sep: nil)
            csv << [data]
    end
end

This is an example of what the csv looks like in a single column:

https://www.url.com/example-page.html
#,
#,,
#,,,
#,,,,
#,,,,,
#,,,,,,
#,,,,,,,
#,,,,,,,,
#,,,,,,,,,
#,,,,,,,,,,
#,,,,,,,,,,,
#,,,,,,,,,,,,
#,,,,,,,,,,,,,
#,,,,,,,,,,,,,,
#,,,,,,,,,,,,,,,
https://anotherexamplepage.html

I was hoping that each array element passed into the method would showcase on the same line but this doesn't appear to be the case. Any help would be much appreciated.

  • Can't you simply use << to fill the csv file? If this has a variable length, you maybe need to fill missing elements somehow beforehand? Potential duplicate https://stackoverflow.com/questions/4822422/output-array-to-csv-in-ruby – Christian May 02 '19 at 21:47
  • `s = a.join(',') #=> "website url,page link,page link,page link"`. Do you simply want to write `s` to a file? If so, why bother with CSV? `File.write(fname, s)` is all you need. – Cary Swoveland May 03 '19 at 05:54
  • Unfortunately, since the method is called multiple times during the process I'm not sure if File.write will work. I do think the a.join method will though. Thank you!! If you want to post that as a solution, once I test it I will accept as an answer. – Andrew Corbett May 08 '19 at 15:27

1 Answers1

0

You don't need to transform the array in any way. Just add it to the CSV:

def dwrite(array)
  CSV.open("filename.csv", "ab") do |csv|
    csv << array
  end
end
infused
  • 24,000
  • 13
  • 68
  • 78