这有效:
f = File.new("myfile").readlines
f[0] #=> "line 1"
f[21] #=> "line 22"
Run Code Online (Sandbox Code Playgroud)
但是,如果我有一个非常大的文件,只需要阅读几行.有没有可能寻找特定的行并在Ruby中读取它们,而无需将文件加载到数组中?
我知道IO流,在那里(如在stdin的情况下)你不能随机搜索流.当然必须有一种方法可以在不加载整个文件的情况下执行此操作.
不要忽视这IO门课. IO::foreach是返回枚举器的方法之一,可以进行延迟计算.
IO#each_line 也是另一个将返回枚举器的人.
在Ruby 2.0中,我们可以调用.lazy和使用那些方法,除了zip和cycle,它们允许我们遍历枚举而不将整个文件放入内存.
为此,您可以使用each_line迭代器,结合使用with_index当前行的行号(从0开始计算):
File.open('myfile') do |file|
file.each_line.with_index do |line, lineno|
case lineno
when 0
# line 1
when 21
# line 22
end
end
end
Run Code Online (Sandbox Code Playgroud)
通过使用open,将块传递给它,而不是new,保证在块执行结束时正确关闭文件.
更新的with_index方法接受一个可选的参数指定要使用的起始索引,所以车上面的代码可以更好地这样写的:
file.each_line.with_index(1) do |line, lineno|
case lineno
when 1
# line 1
end
end
Run Code Online (Sandbox Code Playgroud)