End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
CSV.parse_line
# File tmp/rubies/ruby-3.1.3/lib/csv.rb, line 1804
def parse_line(line, **options)
new(line, **options).each.first
end
Returns the data created by parsing the first line of string or io using the specified options.
-
Argument
stringshould be a String object; it will be put into a newStringIOobject positioned at the beginning. -
Argument
ioshould be anIOobject that is:-
Open for reading; on return, the
IOobject 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:
string = "foo,0\nbar,1\nbaz,2\n" path = 't.csv' File.write(path, string)
Parse the first line from a String object:
CSV.parse_line(string) # => ["foo", "0"]
Parse the first line from a File object:
File.open(path) do |file| CSV.parse_line(file) # => ["foo", "0"] end # => ["foo", "0"]
Returns nil if the argument is an empty String:
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:
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:
CSV.parse_line(string, headers: true) # => #<CSV::Row "Name":"foo" "Count":"0">
Parse the first line from a File object:
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:
# Raises ArgumentError (Cannot parse nil as CSV): CSV.parse_line(nil)