Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

CSV.parse_line

CSV.parse_line(string) → new_array or nil
CSV.parse_line(io) → new_array or nil
CSV.parse_line(string, **options) → new_array or nil
CSV.parse_line(io, **options) → new_array or nil
CSV.parse_line(string, headers: true, **options) → csv_row or nil
CSV.parse_line(io, headers: true, **options) → csv_row or nil

Returns the data created by parsing the first line of string or io using 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 Options for Parsing

Without Option headers

Without option headers, returns the first row as a new Array.

These examples assume prior execution of:

Example
string = "foo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)

Parse the first line from a String object:

Example
CSV.parse_line(string) # => ["foo", "0"]

Parse the first line from a File object:

Example
File.open(path) do |file|
  CSV.parse_line(file) # => ["foo", "0"]
end # => ["foo", "0"]

Returns nil if the argument is an empty String:

Example
CSV.parse_line('') # => nil
With Option headers

With option headers, returns the first row as a CSV::Row object.

These examples assume prior execution of:

Example
string = "Name,Count\nfoo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)

Parse the first line from a String object:

Example
CSV.parse_line(string, headers: true) # => #<CSV::Row "Name":"foo" "Count":"0">

Parse the first line from a File object:

Example
File.open(path) do |file|
  CSV.parse_line(file, headers: true)
end # => #<CSV::Row "Name":"foo" "Count":"0">

Raises an exception if the argument is nil:

Example
# Raises ArgumentError (Cannot parse nil as CSV):
CSV.parse_line(nil)
See also .parse .read .open .readlines also in 3.3 · 3.2 · 3.0