What about something like this?
lines = File.readlines('file.txt')
random_line = lines.shuffle.pop
File.open('file.txt', 'w') do |f|
f.write(lines.join(''))
end
File.open('random.txt', 'a') do |f|
f.write(random_line)
end
Note that readlines
has the effect of reading the whole file into memory, but it also means you get a truly random sample from the file. Your implementation is probably biased more heavily toward the end of the file since you do not know how many lines there are in advance.
As with anything that does manipulation in this way, there is a small chance that the file might be truncated if this program is halted unexpectedly. The usual method to avoid this is to write to a temporary file, then rename when that's successful. A better alternative is to use a database, even an embedded one like SQLite.