22

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
Jon E Kilborn
  • 223
  • 1
  • 2
  • 5

1 Answers1

26

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

Community
  • 1
  • 1
iamcaleberic
  • 913
  • 8
  • 12
  • 1
    Awesome answer. Thank you! – Jon E Kilborn Jan 30 '18 at 21:03
  • Am glad to help – iamcaleberic Jan 30 '18 at 21:10
  • 1
    I suggest you link to relevant parts of Ruby docs, rather than copying part or all of their contents.That way readers can skip the link if they already know what the doc says. Also, without the link readers may have trouble finding the doc for a fuller read. I suggest, for example, "[IO.close](http://ruby-doc.org/core-2.4.0/IO.html#.method-i-close) closes the file and clears any pending writes.". At a minimum, write `close` as `IO#close` – Cary Swoveland Jan 31 '18 at 01:43