From: Mike Fletcher Date: 2006-07-11T10:22:56+09:00 Subject: Re: Write to specified line number of file Aditya Rajgarhia wrote: [...] > I still think there must be a simple way to move to a specified line in > a file. I could write a function which does that by checking for "\n" at > the end of each line, and will do that unless someone can suggest an > easier method soon. Files don't consist of lines, files are ordered sequences of octets. Lines are just an abstraction imposed on files by either the IO libraries and the language you're using, or your editor. Unless the lines in your file are all of the same length it's going to be non-trivial to move them around in place in the file. You'll either need to move the existing contents "up" (if the new line were shorter) or move them "back" (if it's longer). Having said that, you could accomplish your randomizing the file by something along these lines: * read the file line by line and store the offset of the beginning character of each line (using IO#tell and subtracting the length of the line) * open a new temporary output file * randomly pick a line number and use IO#seek to jump to the appropriate offset * read the line and print it to the temp file; remove that line's info from your list of offsets * when there's no more offsets left, close the temp file and File#rename it over the original -- Posted via http://www.ruby-forum.com/.