寻求“0”或使用倒带方法?

Seek to "0" or use rewind method?

如果我想 return 到文件的开头,使用

是否更好
f.seek(0)

f.rewind

例如 "f" 文件句柄?还是只是偏好问题?

它们并不完全相同,因此 更好 取决于意图。 seek 只是移动当前偏移量:

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

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

但是rewind also adjusts lineno:

rewind → 0

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

所以 f.rewind 或多或少等同于:

f.seek(0)
f.lineno = 0

如果您查看 MRI C 实现,您会发现 rewind 就是这样实现的,但是是用 C 而不是 Ruby。

因此,如果您正在处理二进制数据(即没有行号)或者您确定您不关心行号,那么 f.seek(0)f.rewind 在功能上是等价的。

我倾向于使用 rewind,因为它直接表达了我的意图。