ruby-on-rails – .seek在ruby中的含义
发布时间:2020-12-16 22:07:05 所属栏目:百科 来源:网络整理
导读:这个脚本中f.seek(0)的目的是什么?为什么我们需要倒带(current_file),如果该文件已被程序打开? input_file = ARGV[0]def print_all(f) puts f.read()enddef rewind(f) f.seek(0)enddef print_a_line(line_count,f)puts "#{line_count} #{f.readline()}"end
这个脚本中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个位置. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |