How to print a line number in Ruby

2019-02-28 01:13发布

问题:

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

回答1:

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


回答2:

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.