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

2 Answers 2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.