繁体   English   中英

Ruby - 读取文件并打印行号

[英]Ruby - Read file and print line number

这并不容易解释,我还没有找到任何答案。

我希望能够在 Ruby 中读取 .txt 文件并以某种方式能够打印行号。

例子:

#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

我希望这是有道理的,我希望这很容易实现。

提前致谢,里斯

您可以使用Enumerable#each_with_index

为枚举中的每个项目调用带有两个参数(项目及其索引)的块。 给定的参数传递给each()。

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

像Perl一样,Ruby也有特殊变量$. 其中包含文件的行号。

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

打印:

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

如果要将数字放在同一行,请从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

如注释中所述,可以使用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