Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby's CSV.open buffer to memory and write all at once?

Will CSV.open store data in memory and write to file one time when the block exits, or it will automatically write in many batches?

require 'csv'

CSV.open('result.csv', 'wb') do |csv|
  while row = next_row
    csv << row
  end
end
like image 224
eee Avatar asked Dec 09 '15 00:12

eee


People also ask

What is CSV in Ruby?

CSV (comma-separated variables) data is a text representation of a table: A row separator delimits table rows. A common row separator is the newline character "\n" . A column separator delimits fields in a row. A common column separator is the comma character "," .


1 Answers

CSV.open will write to the underlying OS when the block closes, and it will also write every time the buffer fills and is flushed, which will happen automatically. (In my Ruby install, it happens at 8196 bytes.) You can also add csv.flush to your block to force it to write sequentially.

require 'csv'

CSV.open('result.csv', 'wb') do |csv|
  while row = next_row
    csv << row  # Without flush, writes to underlying OS only when buffer fills
    csv.flush   # Adding this forces a write to underlying OS
  end
end             # Exiting block writes to underlying OS and closes file handle

(Note that the writes are to the underlying OS, which may buffer the stream again before actually writing to disk.)

like image 145
user513951 Avatar answered Jan 01 '23 21:01

user513951