简体   繁体   English

Ruby - 读取文件并打印行号

[英]Ruby - Read file and print line number

This isn't going to be easy to explain and I haven't found any answers for it.这并不容易解释,我还没有找到任何答案。

I want to be able to read .txt file in Ruby and somehow be able to print the line number.我希望能够在 Ruby 中读取 .txt 文件并以某种方式能够打印行号。

Example:例子:

#file.txt:
#Hello
#My name is John Smith
#How are you?

File.open("file.txt").each do |line|
   puts line
   puts line.linenumber
end

#First Iteration outputs
#=> Hello
#=> 1

#Second Iteration outputs
#=> My name is John Smith
#=> 2

#Third Iteration outputs
#=> How are you?
#=> 3

I hope this makes sense and I hope it's easily possible.我希望这是有道理的,我希望这很容易实现。

Thanks in advance, Reece提前致谢,里斯

You can use Enumerable#each_with_index : 您可以使用Enumerable#each_with_index

Calls block with two arguments, the item and its index, for each item in enum. 为枚举中的每个项目调用带有两个参数(项目及其索引)的块。 Given arguments are passed through to each(). 给定的参数传递给each()。

File.open(filename).each_with_index do |line, index|
  p "#{index} #{line}"
end

Ruby, like Perl, has the special variable $. 像Perl一样,Ruby也有特殊变量$. which contains the line number of a file. 其中包含文件的行号。

File.open("file.txt").each do |line|
   puts line, $.
end

Prints: 打印:

#Hello
1
#My name is John Smith
2
#How are you?
3

Strip the \\n from line if you want the number on the same line: 如果要将数字放在同一行,请从line删除\\n

File.open("file.txt").each do |line|
   puts "#{line.rstrip} #{$.}"
end

#Hello 1
#My name is John Smith 2
#How are you? 3

As stated in comments, rather than use File.open you can use File.foreach with the benefit of autoclose at the end of the block: 如注释中所述,可以使用File.foreach而不是使用File.open ,而在块末尾可以使用自动关闭功能

File.foreach('file.txt') do |line|
    puts line, $.
end 
# same output...
## Like in PHP ## To get line number __LINE__ ## To get file name __FILE__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM