Method: CSV.parse_row

Defined in:
lib/csv.rb

.parse_row(src, idx, out_dev, fs = nil, rs = nil) ⇒ Object

Parse a line from string. Consider using CSV.parse_line instead. 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

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 '<<(aString)'.
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'.


214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/csv.rb', line 214

def CSV.parse_row(src, idx, out_dev, fs = nil, rs = nil)
  fs ||= ','
  if fs.is_a?(Fixnum)
    fs = fs.chr
  end
  if !rs.nil? and rs.is_a?(Fixnum)
    rs = rs.chr
  end
  idx_backup = idx
  parsed_cells = 0
  res_type = :DT_COLSEP
  begin
    while res_type != :DT_ROWSEP
      res_type, idx, cell = parse_body(src, idx, fs, rs)
      if res_type == :DT_EOS
        if idx == idx_backup #((parsed_cells == 0) and cell.nil?)
          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