微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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个位置.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐