1

I have an array of arrays, where each inner array is a row of data.

I would like to write this as a .csv file.

I am aware of functions in languages other than Ruby that can write a csv in one short function, e.g. R has write.csv(object, "filename.csv")

Is there anything comparable in ruby?

Note: I have used this method, however, I would like something (much) sharper if such a method exists

stevec
  • 41,291
  • 27
  • 223
  • 311

2 Answers2

3

First generate the csv content:

require 'csv'

arr = [['apple', 'mango'], ['lily', 'rose']]
# => [["apple", "mango"], ["lily", "rose"]] 

csv_content = CSV.generate(headers: false) { |csv| arr.each { |row| csv << row } }
# => "apple,mango\nlily,rose\n"

Then simply write the content to csv with:

File.write("my.csv", csv_content)
stevec
  • 41,291
  • 27
  • 223
  • 311
ray
  • 5,454
  • 1
  • 18
  • 40
0

Have a look into these resources;

https://github.com/ruby/csv

https://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html

Also, this;

https://github.com/tilo/smarter_csv/tree/1.2-stable

Sam
  • 1,623
  • 1
  • 19
  • 31