什么.seek在红宝石中意味着什么

Ahm*_*ker 13 ruby linux windows ruby-on-rails

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)
Run Code Online (Sandbox Code Playgroud)

小智 22

它寻求("去","试图找到")流中的给定位置(作为整数).在您的代码中,您定义了一个名为rewindwhich 的新方法.当你打电话给它

rewind(current_file)
Run Code Online (Sandbox Code Playgroud)

您发送current_file(您从磁盘或其他任何地方打开的文件),其定义为:

current_file = File.open(input_file)
Run Code Online (Sandbox Code Playgroud)

到倒带方法,它将"寻找"到位置0,这是文件的开头.

例如,您可以创建另一个调用almost_rewind和写入的方法:

def almost_rewind(f)
  f.seek(-10)
end
Run Code Online (Sandbox Code Playgroud)

这将在你的流中返回10个位置.

  • 感谢尼古拉,他是唯一一个有足够诚信回答的人.你的答案比Ruby文档更清晰.如果只有更多的SOers像你一样. (5认同)
  • 如果只编写了Ruby文档,那么那些尚未知道答案的人就会阅读这些文档. (4认同)