Search code examples
ruby-on-railsrubystringio

What does the .rewind method do on a Tempfile in ruby?


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

Solution

  • 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 ("").