Method: CSV#read

Defined in:
lib/csv.rb

#readObject Also known as: readlines

:call-seq:

csv.read -> array or csv_table

Forms the remaining rows from self into:

  • A CSV::Table object, if headers are in use.

  • An Array of Arrays, otherwise.

The data source must be opened for reading.

Without headers:

string = "foo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
csv = CSV.open(path)
csv.read # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]

With headers:

string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
path = 't.csv'
File.write(path, string)
csv = CSV.open(path, headers: true)
csv.read # => #<CSV::Table mode:col_or_row row_count:4>

Raises an exception if the source is not opened for reading:

string = "foo,0\nbar,1\nbaz,2\n"
csv = CSV.new(string)
csv.close
# Raises IOError (not opened for reading)
csv.read


2595
2596
2597
2598
2599
2600
2601
2602
# File 'lib/csv.rb', line 2595

def read
  rows = to_a
  if parser.use_headers?
    Table.new(rows, headers: parser.headers)
  else
    rows
  end
end