Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 402
Jon E Kilborn Avatar asked Jan 30 '18 20:01

Jon E Kilborn


People also ask

What is Tempfile Ruby?

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.

How do you write to a file in Ruby?

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.


1 Answers

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

like image 175
iamcaleberic Avatar answered Oct 21 '22 07:10

iamcaleberic