Ruby printing line numbers -
this question has answer here:
- how print line number in ruby 2 answers
i'm trying check file line line starting white space. want lines start space or tab not both. if there line starts space , anthers line starts tab in file code below going print warning, on top of want print 2 lines 1 starts space , 1 starts tab show user, , im stuck on how line numbers , stuff. help!! code looks far.
file= file.read("file_tobe_checked") tabs = spaces = false file.each |line| line =~ /^\t/ , tabs = true line =~ /^ / , spaces = true if spaces , tabs stderr << "the white spaces @ beginning of each line not consistent.\n" end end
ruby has number of special variables, 1 of $. read line's number.
you can use io's lineno method.
io.lineno (from ruby core) ------------------------------------------------------------------------------ ios.lineno -> integer ------------------------------------------------------------------------------ returns current line number in ios. stream must opened reading. lineno counts number of times #gets called rather number of newlines encountered. 2 values differ if #gets called separator other newline. methods use $/ #each, #lines , #readline increment lineno. see $. variable. f = file.new("testfile") f.lineno #=> 0 f.gets #=> "this line one\n" f.lineno #=> 1 f.gets #=> "this line two\n" f.lineno #=> 2
Comments
Post a Comment