这并不容易解释,而且我还没有找到任何答案。
我希望能够在 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
Run Code Online (Sandbox Code Playgroud)
我希望这是有道理的,并且我希望它很容易成为可能。
提前致谢,里斯
Ruby 和 Perl 一样,有一个特殊的变量$.,其中包含文件的行号。
File.open("file.txt").each do |line|
puts line, $.
end
Run Code Online (Sandbox Code Playgroud)
印刷:
#Hello
1
#My name is John Smith
2
#How are you?
3
Run Code Online (Sandbox Code Playgroud)
如果您希望数字位于同一行,请去掉以下\n内容:line
File.open("file.txt").each do |line|
puts "#{line.rstrip} #{$.}"
end
#Hello 1
#My name is John Smith 2
#How are you? 3
Run Code Online (Sandbox Code Playgroud)
File.open如评论中所述,您可以使用File.foreach代替使用,并在块末尾具有自动关闭的优点:
File.foreach('file.txt') do |line|
puts line, $.
end
# same output...
Run Code Online (Sandbox Code Playgroud)