# CSV (Class)

In: | csv.rb
Parent: | Object

This module is copyrighted free software by NAKAMURA, Hiroshi. You can redistribute it and/or modify it under the same term as Ruby.

## Methods

generate generate_line generate_row open parse parse_line parse_row

## Classes and Modules

Class CSV::BasicWriter
Class CSV::Cell
Class CSV::IOBuf
Class CSV::IOReader
Class CSV::IllegalFormatError
Class CSV::Reader
Class CSV::Row
Class CSV::StreamBuf
Class CSV::StringReader
Class CSV::Writer

## Public Class methods

open(filename, mode, col_sep = ?,, row_sep = nil, &block)

SYNOPSIS

      1. reader = CSV.open(filename, 'r')

      2. CSV.open(filename, 'r') do |row|
           ...
         end

      3. writer = CSV.open(filename, 'w')

      4. CSV.open(filename, 'w') do |writer|
           ...
         end

ARGS

      filename: filename to open.
      mode: 'r' for read (parse)
            'w' for write (generate)
      row: an Array of cells which is a parsed line.
      writer: Created writer instance.  See CSV::Writer#<< and
        CSV::Writer#add_row to know how to generate CSV string.

RETURNS

      reader: Create reader instance.  To get parse result, see
        CSV::Reader#each.
      writer: Created writer instance.  See CSV::Writer#<< and
        CSV::Writer#add_row to know how to generate CSV string.

DESCRIPTION

      Open a CSV formatted file to read or write.

EXAMPLE 1

      reader = CSV.open('csvfile.csv', 'r')
      row1 = reader.shift
      row2 = reader.shift
      if row2.empty?
        p 'row2 not find.'
      end
      reader.close

EXAMPLE 2

      CSV.open('csvfile.csv', 'r') do |row|
        p row
      end

EXAMPLE 3

      writer = CSV.open('csvfile.csv', 'w')
      writer << ['r1c1', 'r1c2'] << ['r2c1', 'r2c2'] << [nil, nil]
      writer.close

EXAMPLE 4

      CSV.open('csvfile.csv', 'w') do |writer|
        writer << ['r1c1', 'r1c2']
        writer << ['r2c1', 'r2c2']
        writer << [nil, nil]
      end

[Source]

    # File csv.rb, line 192
      def CSV.open(filename, mode, col_sep = ?,, row_sep = nil, &block)
        if mode == 'r' or mode == 'rb'
          open_reader(filename, col_sep, row_sep, &block)
        elsif mode == 'w' or mode == 'wb'
          open_writer(filename, col_sep, row_sep, &block)
        else
          raise ArgumentError.new("'mode' must be 'r', 'rb', 'w', or 'wb'")
        end
      end

parse(filename, col_sep = ?,, row_sep = nil, &block)

[Source]

    # File csv.rb, line 202
      def CSV.parse(filename, col_sep = ?,, row_sep = nil, &block)
        open_reader(filename, col_sep, row_sep, &block)
      end

generate(filename, col_sep = ?,, row_sep = nil, &block)

[Source]

    # File csv.rb, line 206
      def CSV.generate(filename, col_sep = ?,, row_sep = nil, &block)
        open_writer(filename, col_sep, row_sep, &block)
      end

parse_line(src, col_sep = ?,, row_sep = nil)

SYNOPSIS

      cells = CSV.parse_line(src, col_sep = ?,, row_sep = nil)

ARGS

      src: a CSV String.
      col_sep: Column separator.  ?, by default.  If you want to separate
        fields with semicolon, give ?; here.
      row_sep: Row separator.  nil by default.  nil means "\r\n or \n".  If you
        want to separate records with \r, give ?\r here.

RETURNS

      cells: an Array of parsed cells in first line.  Each cell is a String.

DESCRIPTION

      Parse one line from given string.  Bare in mind it parses ONE LINE.  Rest
      of the string is ignored for example "a,b\r\nc,d" => ['a', 'b'] and the
      second line 'c,d' is ignored.

      If you don't know whether a target string to parse is exactly 1 line or
      not, use CSV.parse_row instead of this method.

[Source]

    # File csv.rb, line 726
      def CSV.parse_line(src, col_sep = ?,, row_sep = nil)
        idx = 0
        res_type = :DT_COLSEP
        cells = Row.new
        begin
          while (res_type.equal?(:DT_COLSEP))
            cell = Cell.new
            res_type, idx = parse_body(src, idx, cell, col_sep, row_sep)
            cells.push(cell.is_null ? nil : cell.data)
          end
        rescue IllegalFormatError
          return Row.new
        end
        cells
      end

generate_line(cells, col_sep = ?,, row_sep = nil)

SYNOPSIS

      str = CSV.generate_line(cells, col_sep = ?,, row_sep = nil)

ARGS

      cells: an Array of cell to be converted to CSV string.  Each cell must
        respond to 'to_s'.
      col_sep: Column separator.  ?, by default.  If you want to separate
        fields with semicolon, give ?; here.
      row_sep: Row separator.  nil by default.  nil means "\r\n or \n".  If you
        want to separate records with \r, give ?\r here.

RETURNS

      str: a String of generated CSV string.

DESCRIPTION

      Create a line from cells.  Each cell is stringified by to_s.

[Source]

    # File csv.rb, line 760
      def CSV.generate_line(cells, col_sep = ?,, row_sep = nil)
        if (cells.size == 0)
          return ''
        end
        res_type = :DT_COLSEP
        result_str = ''
        idx = 0
        while true
          cell = if (cells[idx].nil?)
              Cell.new('', true)
            else
              Cell.new(cells[idx].to_s, false)
            end
          generate_body(cell, result_str, col_sep, row_sep)
          idx += 1
          if (idx == cells.size)
            break
          end
          generate_separator(:DT_COLSEP, result_str, col_sep, row_sep)
        end
        result_str
      end

parse_row(src, idx, out_dev, col_sep = ?,, row_sep = nil)

SYNOPSIS

      parsed_cells, idx = CSV.parse_row(src, idx, out_dev, col_sep = ?,, row_sep = nil)

ARGS

      src: a CSV data to be parsed.  Must respond '[](idx)'.
        src[](idx) must return a char. (Not a string such as 'a', but 97).
        src[](idx_out_of_bounds) must return nil.  A String satisfies this
        requirement.
      idx: index of parsing location of 'src'.  0 origin.
      out_dev: buffer for parsed cells.  Must respond '<<(CSV::Cell)'.
      col_sep: Column separator.  ?, by default.  If you want to separate
        fields with semicolon, give ?; here.
      row_sep: Row separator.  nil by default.  nil means "\r\n or \n".  If you
        want to separate records with \r, give ?\r here.

RETURNS

      parsed_cells: num of parsed cells.
      idx: index of next parsing location of 'src'.

DESCRIPTION

      Parse a line from string.  To parse lines in CSV string, see EXAMPLE
      below.

EXAMPLE

      src = "a,b\r\nc,d\r\ne,f"
      idx = 0
      begin
        parsed = []
        parsed_cells, idx = CSV.parse_row(src, idx, parsed)
        puts "Parsed #{ parsed_cells } cells."
        p parsed
      end while parsed_cells > 0

[Source]

    # File csv.rb, line 816
      def CSV.parse_row(src, idx, out_dev, col_sep = ?,, row_sep = nil)
        idx_backup = idx
        parsed_cells = 0
        res_type = :DT_COLSEP
        begin
          while (!res_type.equal?(:DT_ROWSEP))
            cell = Cell.new
            res_type, idx = parse_body(src, idx, cell, col_sep, row_sep)
            if res_type.equal?(:DT_EOS)
              if idx == idx_backup #((parsed_cells == 0) && (cell.is_null))

                return 0, 0
              end
              res_type = :DT_ROWSEP
            end
            parsed_cells += 1
            out_dev << cell
          end
        rescue IllegalFormatError
          return 0, 0
        end
        return parsed_cells, idx
      end

generate_row(src, cells, out_dev, col_sep = ?,, row_sep = nil)

SYNOPSIS

      parsed_cells = CSV.generate_row(src, cells, out_dev, col_sep = ?,, row_sep = nil)

ARGS

      src: an Array of CSV::Cell to be converted to CSV string.  Must respond to
        'size' and '[](idx)'.  src[idx] must return CSV::Cell.
      cells: num of cells in a line.
      out_dev: buffer for generated CSV string.  Must respond to '<<(string)'.
      col_sep: Column separator.  ?, by default.  If you want to separate
        fields with semicolon, give ?; here.
      row_sep: Row separator.  nil by default.  nil means "\r\n or \n".  If you
        want to separate records with \r, give ?\r here.

RETURNS

      parsed_cells: num of converted cells.

DESCRIPTION

      Convert a line from cells data to string.  To generate multi-row CSV
      string,  See EXAMPLE below.

EXAMPLE

      def d(str)
        CSV::Cell.new(str, false)
      end

      row1 = [d('a'), d('b')]
      row2 = [d('c'), d('d')]
      row3 = [d('e'), d('f')]
      src = [row1, row2, row3]
      buf = ''
      src.each do |row|
        parsed_cells = CSV.generate_row(row, 2, buf)
        puts "Created #{ parsed_cells } cells."
      end
      p buf

[Source]

    # File csv.rb, line 875
      def CSV.generate_row(src, cells, out_dev, col_sep = ?,, row_sep = nil)
        src_size = src.size
        if (src_size == 0)
          if cells == 0
            generate_separator(:DT_ROWSEP, out_dev, col_sep, row_sep)
          end
          return 0
        end
        res_type = :DT_COLSEP
        parsed_cells = 0
        generate_body(src[parsed_cells], out_dev, col_sep, row_sep)
        parsed_cells += 1
        while ((parsed_cells < cells) && (parsed_cells != src_size))
          generate_separator(:DT_COLSEP, out_dev, col_sep, row_sep)
          generate_body(src[parsed_cells], out_dev, col_sep, row_sep)
          parsed_cells += 1
        end
        if (parsed_cells == cells)
          generate_separator(:DT_ROWSEP, out_dev, col_sep, row_sep)
        else
          generate_separator(:DT_COLSEP, out_dev, col_sep, row_sep)
        end
        parsed_cells
      end

[Validate]