Writing to specific lines in a File
-
Lets say I have a file with 100 lines. I would like to open that file, and insert a line before line X (lets say line 50). Is that possible without loading the whole file into an array with
readlines
?Chris
-
Good question... never tried it.
You can set the current line via
lineno=()
, but I suspect theseIO
file functions (whichFile
inherits,) are sequential files, and usingputs()
after setting the line, is likely to overwrite that line.Perhaps you may wish to look in the standard Ruby Extended libs for a Random Access File extension ??
-
OH !! Chris ... didn't realize this.. there's a
TempFile
manager class in the standard Ruby library.Also there's the
PStore
class, which is like a file-basedHash
.There's also a "massive"
CSV
class. -
Awesome Dan, thanks! I'll go look into those.
Advertisement