0

Let's say I am using code like this to make inline edits of CSV file:

CSV.open(fn, 'r+') do |f|
  old_pos = f.pos
  while r = f.shift
    if r[0] == 'NOT_PROCESSED'
      f.seek(old_pos)
      r[0] = 'PASSED       ' # pay attention to the padding spaces!
      f << r
    end

    old_pos = f.pos
  end
end

Is there a way to somehow use headers with this approach? Like for example r['STATUS']? How should I rewrite code to make this possible?

1
  • The idea to edit csv-files in place seem quite dangerous to me. I would either write to a new file, or use some dbm-database when really need to do in-edting of a file. Commented Mar 3, 2016 at 8:52

1 Answer 1

1

CSV.open has a third parameter called options, where you can add various options, including :headers:

:headers
If set to :first_row or true, the initial row of the CSV file will be treated as a row of headers. If set to an Array, the contents will be used as the headers. If set to a String, the String is run through a call of ::parse_line with the same :col_sep, :row_sep, and :quote_char as this instance to produce an Array of headers. This setting causes #shift to return rows as CSV::Row objects instead of Arrays and #read to return CSV::Table objects instead of an Array of Arrays.

CSV.open(fn, 'r+', headers: true) do |f|
  old_pos = f.pos
  while r = f.shift
    if r['STATUS'] == 'NOT_PROCESSED'
      f.seek(old_pos)
      r['STATUS'] = 'PASSED       ' # pay attention to the padding spaces!
      f << r
    end

    old_pos = f.pos
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.