Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seek to "0" or use rewind method?

Tags:

file

ruby

If I wish to return to the start of a file, is it better to use

f.seek(0)

or

f.rewind

for the example "f" file handle? Or is it just a matter of preference?

like image 204
Friedrich 'Fred' Clausen Avatar asked Dec 27 '25 19:12

Friedrich 'Fred' Clausen


1 Answers

They're not quite the same thing so better depends on intent. seek just moves the current offset around:

seek(amount, whence=IO::SEEK_SET) → 0

Seeks to a given offset anInteger in the stream according to the value of whence: ...

but rewind also adjusts lineno:

rewind → 0

Positions ios to the beginning of input, resetting lineno to zero.

so f.rewind is more or less the same as:

f.seek(0)
f.lineno = 0

If you look at the MRI C implementation, you'll see that rewind is implemented just like that but in C rather than Ruby.

So if you're working with binary data (i.e. no line numbers) or you're sure you don't care about line numbers, then f.seek(0) and f.rewind are functionally equivalent.

I'd tend to use rewind because it directly expresses my intent.

like image 161
mu is too short Avatar answered Dec 30 '25 08:12

mu is too short