如何在Ruby中打印行号

我正在尝试通过一个文件来检查它开始的空白区域的每一行。 我们想用空格作为开头或标签。 如果一行以空格开头而另一行以制表符开头,我想通知用户白色空格不一致。 一个例子我想打印一行以空格开头,一行以制表符开头。 而我坚持得到行号部分。 我尝试使用file.gets来获得第一个空白区域,但它对我不起作用(所以我没有在下面的代码中包含它)。 帮助我如何打印行号。

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 

您应该能够使用file.lineno来获取您在文件中读取的当前行的编号。

 file = File.open("file_name") file.each do |line| ... puts "#{file.lineno}: #{line}" # Outputs the line number and the content of the line end 

根据@ zajn的回答:

 file = File.open("filename.txt") file.each do |line| puts "#{file.lineno}: #{line}" end 

或者您可以使用’each with index’:

 File.open("another_file.txt").each_with_index do |line,i| puts "#{i}: #{line}" end 

看起来不那么神奇。