Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can the Ruby File#read or File#readlines only be used once?

Tags:

ruby

Why can Ruby's File#read and File#readlines only be used once?

For example:

txt = File.open "test.txt"
puts txt.read  # returns the content
puts txt.read  # returns ""
like image 324
Alex Avatar asked Dec 03 '22 05:12

Alex


1 Answers

When you call File.open you are opening an I/O stream to the file. Internally, the stream has a "cursor," which represents what part of it you read from last. When you call File#read with no length argument, it reads from the cursor (which starts at the beginning of the file when you open it) until the end of the stream, i.e. the end of the file. In so doing, the cursor is also moved to the end of the file. If you call read again, then, the cursor is still at the end of the file, and since there is nothing more for it to read it returns nothing ("").

If you need to read the file a second time you can move the cursor back to the beginning of the stream using File#rewind.

like image 110
Jordan Running Avatar answered Jan 11 '23 23:01

Jordan Running