Method: File.edit_lines

Defined in:
lib/pleasant_path/file.rb

.edit_lines(filename, eol: $/) {|lines| ... } ⇒ Array<String>

Reads the file indicated by filename, and yields the entire contents as an Array of lines to the given block for editing. Writes the return value of the block back to the file, overwriting previous contents. eol (end-of-line) characters are stripped from each line when reading, and appended to each line when writing. Returns the return value of the block.

Examples:

Dedup lines of file

File.read("entries.txt")  # == "AAA\nBBB\nBBB\nCCC\nAAA\n"

File.edit_lines("entries.txt", &:uniq)
  # == ["AAA", "BBB", "CCC"]

File.read("entries.txt")  # == "AAA\nBBB\nCCC\n"

Parameters:

Yields:

  • (lines)

Yield Parameters:

Yield Returns:

Returns:



78
79
80
81
82
83
84
85
86
# File 'lib/pleasant_path/file.rb', line 78

def self.edit_lines(filename, eol: $/)
  self.open(filename, "r+") do |f|
    lines = yield f.read_lines(eol: eol)
    f.seek(0, IO::SEEK_SET)
    f.write_lines(lines, eol: eol)
    f.truncate(f.pos)
    lines
  end
end