26

I think I'm missing something really obvious here, but what is the second argument that everyone puts in for CSV.open method, in this case its 'wb', I've seen other letter(s) put here, but no one really explains what it does. What does it do?

CSV.open("path/to/file.csv", "wb") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

The ruby doc doesn't seem to give any explanation. http://www.ruby-doc.org/stdlib-2.0/libdoc/csv/rdoc/CSV.html

Thanks!

StickMaNX
  • 1,982
  • 2
  • 16
  • 13

2 Answers2

41

From the IO Open Mode documentation:

"r" Read-only, starts at beginning of file (default mode).

"r+" Read-write, starts at beginning of file.

"w" Write-only, truncates existing file to zero length or creates a new file for writing.

"w+" Read-write, truncates existing file to zero length or creates a new file for reading and writing.

"a" Write-only, starts at end of file if file exists, otherwise creates a new file for writing.

"a+" Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing.

James
  • 4,599
  • 2
  • 19
  • 27
  • 13
    For anyone too lazy to follow the link: the `b` suffix means "binary" file mode (which "Suppresses EOL <-> CRLF conversion on Windows. And sets external encoding to ASCII-8BIT unless explicitly specified."); the `t` suffix means "text" file mode – Alec May 04 '17 at 10:40
0

File mode. It describes how the file being opened is treated.

See this answer for more info on ruby file modes: What are the Ruby File.open modes and options?

Community
  • 1
  • 1
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337