簡體   English   中英

如何在Ruby中打印行號

[英]How to print a line number in Ruby

我正在嘗試檢查一個文件,以檢查每行以什么空白開始。 我們想使用空格作為開始或選項卡。 如果一行以空格開頭,另一行以制表符開頭,我想通知用戶空白不一致。 還有一個示例,我要打印以空格開頭的一行和以tab開頭的一行。 我堅持要獲取行號部分。 我嘗試使用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

或者您可以使用“每個帶有索引”:

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

看起來有點神奇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM