How to print a line number in Ruby

后端 未结 2 431
独厮守ぢ
独厮守ぢ 2021-01-24 21:49

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 wi

相关标签:
2条回答
  • 2021-01-24 22:25

    Based on @zajn's answer:

    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.

    0 讨论(0)
  • 2021-01-24 22:35

    You should be able to use file.lineno to get the number of the current line you are reading in the file.

    file = File.open("file_name")
    file.each do |line|
      ...
      puts "#{file.lineno}: #{line}" # Outputs the line number and the content of the line
    end
    
    0 讨论(0)
提交回复
热议问题