ruby-on-rails – .seek在ruby中的含义

这个脚本中f.seek(0)的目的是什么?为什么我们需要倒带(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)

解决方法

它在流中寻找(“去”,“尝试找到”)给定位置(作为整数).在您的代码中,您定义了一个称为rewind的新方法,它接受一个参数.当你打电话时
rewind(current_file)

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

current_file = File.open(input_file)

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

你可以使用另一个名为almost_rewind的方法来写:

def almost_rewind(f)
  f.seek(-10)
end

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...