简体   繁体   中英

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. 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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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