I've looked through these docs and Google, and can't seem to find the purpose of .rewind
, and how it differs from .close
, in the context of working with a Tempfile
.
Also, why does .read
return an empty string before rewinding?
Here is an example:
file = Tempfile.new('foo')
file.path # => A unique filename in the OS's temp directory,
# e.g.: "/tmp/foo.24722.0"
# This filename contains 'foo' in its basename.
file.write("hello world")
file.rewind
file.read # => "hello world"
file.close
file.unlink # deletes the temp file
A utility class for managing temporary files. When you create a Tempfile object, it will create a temporary file with a unique filename. A Tempfile objects behaves just like a File object, and you can perform all the usual file operations on it: reading data, writing data, changing its permissions, etc.
Writing to a file with Ruby Writing text to a file with Ruby is reasonably straightforward. Just like many other languages, you need to open the file in "write" mode, write your data, and then close the file.
Rewind - Read more about it on ruby docs
IO#Close - Read more on the ruby docs
Read - Read more on the ruby docs
Summary
rewind
Positions ios to the beginning of input, resetting lineno to zero. Rewind resets the line number to zero
f = File.new("testfile")
f.readline #=> "This is line one\n"
f.rewind #=> 0
f.lineno #=> 0
f.readline #=> "This is line one\n"
IO#close
Closes ios and flushes any pending writes to the operating system.read([length [, outbuf]])
Reads length bytes from the I/O stream. Length must be a non-negative integer or nil. If length is zero, it returns an empty string ("").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With