如何在 Ruby 中打印行号 [英] How to print a line number in Ruby
问题描述
我试图通过一个文件来检查每一行以什么空格开头.我们想使用空格作为开始或制表符.如果一行以空格开头,另一行以制表符开头,我想通知用户空格不一致.还有一个例子,我想打印一行以空格开头和一行以制表符开头.我坚持获取行号部分.我试过 file.gets 来获得第一个空格,但它对我不起作用(所以我没有在下面的代码中包含它).帮助我如何打印行号.
I'm trying to go through a file to check every line with what white space it starts. we want to use space as a start or a tab. If one line starts with space and another line with tab I want to inform the user that the white spaces are not consistent. And an example I want to print one line that starts with space and one line that starts with tab. And Im stuck at the getting the line number part. I tried file.gets to get the first white space but it isnt working for me(so I didnt include it in my code below). Help how do I print the line number.
tabs = spaces = false
file = File.read("file_name")
file.each do |line|
line =~ /^\t/ and tabs = true
line =~ /^ / and spaces = true
if spaces and tabs
puts "The white spaces at the beginning of each line are not consistent.\n"
break
end
end
推荐答案
基于@zajn 的回答:
Based on @zajn's answer:
file = File.open("filename.txt")
file.each do |line|
puts "#{file.lineno}: #{line}"
end
或者你可以使用'each with index':
Or you could use 'each with index':
File.open("another_file.txt").each_with_index do |line,i|
puts "#{i}: #{line}"
end
看起来不那么神奇.
这篇关于如何在 Ruby 中打印行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!