在Ruby中,.seek是什么意思?

15

在这个脚本中,f.seek(0)的目的是什么?如果该文件已经被程序打开,为什么我们需要rewind(current_file)

input_file = ARGV[0]

def print_all(f)
    puts f.read()
end

def rewind(f)
    f.seek(0)
end

def print_a_line(line_count,f)
puts "#{line_count} #{f.readline()}"
end

current_file = File.open(input_file)

puts "First Let's print the whole file:"
puts # a blank line

print_all(current_file)

puts "Now Let's rewind, kind of like a tape"

rewind(current_file)

puts "Let's print the first line:"

current_line = 1
print_a_line(current_line, current_file)

1
http://ruby-doc.org/core-2.0/IO.html#method-i-seek - Matt
1
它在名为 rewind 的方法内部,这不会给你提示吗?如果不行,您能看一下文档吗? - user229044
我已经完成了,我解决了它,无论如何还是谢谢。 - Ahmed Taker
你需要养成首先查阅文档的习惯。前往 http://ruby-doc.org/core-2.0/ 或者 http://ruby-doc.org/stdlib-2.0.0/ 进行搜索,或者在终端窗口输入 ri seek - the Tin Man
15
人们似乎认为,只要在网络上有“解释”,比如Ruby文档,就会自动让新手明白。但事实并非如此。我目前正在解决这个问题,有着同样的疑问。我查看了文档(在谷歌上排名第一),但对我来说毫无意义。这篇文章在搜索结果中排名第二,更令人惊讶的是,SO的管理员关闭了这个话题,再次证明SO不适合新手。感谢@Nikolai Manek抽出时间回答问题,而不是成为一个典型的SO AH。 - Padawan
1
https://learnrubythehardway.org/book/ex20.html - CodeFinity
1个回答

23

它寻找(“前往”,“尝试查找”)流中给定的位置(作为整数)。在您的代码中,您定义了一个名为rewind的新方法,它接受一个参数。当您使用此方法并调用它时

rewind(current_file)

你发送当前文件(从磁盘或其他任何地方打开的文件),定义如下:


current_file = File.open(input_file)

将 "rewind" 方法应用到文件中,它将“寻找”到位置0,即文件的开头。

你还可以创建另一个名为almost_rewind的方法并编写:

def almost_rewind(f)
  f.seek(-10, IO::SEEK_END)
end

这将从流的末尾开始,向后移10个位置。


5
谢谢你,Nikolai。因为你是唯一一个有足够诚信回答的人,你的回答比 Ruby 文档清晰得多。如果能有更多像你这样的 Stack Overflow 用户就好了。 - Padawan
4
如果 Ruby 文档是为那些不知道答案的人编写的,那该多好。 - android.weasel
1
f.seek(-10) or passing even -1 always generates: Invalid argument @ rb_io_seek - test.txt (Errno::EINVAL) - CodeFinity
在查看了http://ruby-doc.org/core-2.2.2/IO.html#method-i-seek之后,我相信像`f.seek(-10,IO :: SEEK_CUR)`这样的东西会起作用。当使用负值时,您必须给它一个起始点(在这种情况下为当前位置)向后移动。如果是单个参数,则必须是正的'real'字符位置。 - CodeFinity
@codeFinity - 是的,我已经使用了SEEK::END更新了我的示例。你是对的 :) - Nikolai Manek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接