简体   繁体   English

如何在Ruby中打印行号

[英]How to print a line number in Ruby

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. 还有一个示例,我要打印以空格开头的一行和以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). 我尝试使用file.gets获得第一个空格,但是它对我不起作用(所以我没有在下面的代码中包含它)。 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

You should be able to use file.lineno to get the number of the current line you are reading in the file. 您应该能够使用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

Based on @zajn's answer: 基于@zajn的答案:

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

Or you could use 'each with index': 或者您可以使用“每个带有索引”:

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

which looks a touch less magical. 看起来有点神奇。

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

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