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?
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.
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