0

Though it seems far more common for people to use the Ruby CSV class methods, I have an occasion to use a CSV instance, but it seams completely uncooperative.

What I'd like to do is create a CSV instance, add some rows to it, then be able to retrieve all those rows and write them to a file. Sadly, the following code doesn't work as I would like at all.

require 'csv'

csv = CSV.new('', headers: ['name', 'age'])
csv.read # Apparently I need to do this so that the headers are actually read in.

csv.add_row(['john', '22'])
csv.add_row(['jane', '24'])
csv.read

csv.to_a
csv.to_s

All I want to be able to retrieve the information I put into the csv and then write that to a file, but I can't seem to do that :/

What am I doing wrong?

0

1 Answer 1

3

You need to use CSV#rewind

Here is the sample:

require 'csv'

csv = CSV.new(File.new("data1.csv", "r+"), headers: ['name', 'age'], write_headers: true)

csv.add_row(['john', '22'])
csv.add_row(['jane', '24'])

p csv.to_a  # Empty array

csv.rewind

p csv.to_a  # Array with three CSV::Row objects (including header)
Sign up to request clarification or add additional context in comments.

2 Comments

Be careful with rewind, because it moves CSV's concept of the file placeholder back to the top, and any subsequent add_row statements would be inserted at the top of the file, not at the bottom where we'd expect.
Rewind seems like a bit of hack to achieve what I want (which seems weird to me since I feel like my use case is not abnormal), but it does work -- thank you! Follow up: After csv.rewind, is this a better way to then write this to a file (in CSV format)than this: csv.map(&:to_s).join(',')

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.