确定 Ruby 中的最后一行
我想知道如何确定何时位于我读入的文件的最后一行。我的代码看起来像是
File.open(file_name).each do |line|
if(someway_to_determine_last_line)
end
我注意到有一个 file.eof?方法,但是在读取文件时如何调用该方法?谢谢!
I'm wondering how I can determine when I am on the last line of a file that I reading in. My code looks like
File.open(file_name).each do |line|
if(someway_to_determine_last_line)
end
I noticed that there is a file.eof? method, but how would I call the method as the file is being read? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用
each
迭代文件,那么最后一行将在到达文件末尾之后传递到块,因为最后一行是,根据定义,该行以 EOF 结尾。因此只需在块中调用
file.eof?
即可。如果您想确定它是否是文件中的最后一个非空行,您必须实现某种预读。
If you're iterating the file with
each
, then the last line will be passed to the block after the end-of-file is reached, because the last line is, by definition, the line ending with EOF.So just call
file.eof?
in the block.If you'd like to determine if it's the last non-empty line in the file, you'd have to implement some kind of readahead.
根据您需要对“最后一个非空行”执行的操作,您可能可以执行以下操作:
Depending on what you need to do with this "last non-empty line", you might be able to do something like this:
秘密武器是
.to_a
获取第一行:
获取最后一行:
获取文件的 n 行:
获取行数:
Secret sauce is
.to_a
Get the first line:
Get the last line:
Get the n line of a file:
Get the count of lines:
fd.eof?
可以工作,但只是为了好玩,这里有一个适用于任何类型的枚举器的通用解决方案(Ruby 1.9):输出:
fd.eof?
works, but just for fun, here's a generic solution that works with any kind of enumerators (Ruby 1.9):Which outputs:
打开文件并使用 readline 方法:
要简单地操作文件的最后一行,请执行以下操作:
第 1 行将文件作为行数组读取
第 2 行使用该对象并迭代每个对象
第 3 行测试当前行是否匹配 匹配,则最后一行
如果与
第 5 行和第 5 行 第 4 行将起作用。 6 不匹配情况的处理行为
Open your file and use the readline method:
To simply manipulate last line of file do the following:
Line 1 reads the file in as an array of lines
Line 2 uses that object and iterates over each of them
Line 3 tests if the current line matches the last line
Line 4 acts if it's a match
Line 5 & 6 handle behavior for non-matching circumstance