Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

CSV.new

CSV.new(string)
CSV.new(io)
CSV.new(string, **options)
CSV.new(io, **options)

Returns the new CSV object created using string or io and the specified options.

  • Argument string should be a String object; it will be put into a new StringIO object positioned at the beginning.

  • Argument io should be an IO object that is:

    • Open for reading; on return, the IO object will be closed.

    • Positioned at the beginning. To position at the end, for appending, use method CSV.generate. For any other positioning, pass a preset StringIO object instead.

  • Argument options: See:

    For performance reasons, the options cannot be overridden in a CSV object, so those specified here will endure.

In addition to the CSV instance methods, several IO methods are delegated. See Delegated Methods.


Create a CSV object from a String object:

Example
csv = CSV.new('foo,0')
csv # => #<CSV io_type:StringIO encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">

Create a CSV object from a File object:

Example
File.write('t.csv', 'foo,0')
csv = CSV.new(File.open('t.csv'))
csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">

Raises an exception if the argument is nil:

Example
# Raises ArgumentError (Cannot parse nil as CSV):
CSV.new(nil)
See also .instance .open .generate_lines .parse also in 3.2 · 3.1 · 3.0