红宝石印刷行号

时间:2014-08-18 19:46:52

标签: ruby line whitespace

我试图逐行检查文件以启动空白区域。我希望所有的行都以空格或制表符开头,而不是两者。如果有一个以空格开头的行和以该文件中的制表符开头的花药行,则下面的代码将打印警告,但最重要的是我要打印2行,一行以空格开头,一行以a开头选项卡只是为了显示用户,我坚持如何获取行号和东西。救命!!到目前为止,我的代码看起来像这样。

    file= File.read("file_tobe_checked")
    tabs = spaces = false
    file.each do |line|

    line =~ /^\t/ and tabs = true
    line =~ /^ / and spaces = true  

    if spaces and tabs
    STDERR <<  "The white spaces at the beginning of each line are not consistent.\n"

    end
    end

2 个答案:

答案 0 :(得分:1)

Ruby有许多特殊变量,其中一个是$.,它是当前读取行的编号。

您也可以使用IO的lineno方法。

IO.lineno

(from ruby core)
------------------------------------------------------------------------------
  ios.lineno    -> integer

------------------------------------------------------------------------------

Returns the current line number in ios.  The stream must be opened for
reading. lineno counts the number of times #gets is called rather than the
number of newlines encountered.  The two values will differ if #gets is called
with a separator other than newline.

Methods that use $/ like #each, #lines and #readline will also increment
lineno.

See also the $. variable.

  f = File.new("testfile")
  f.lineno   #=> 0
  f.gets     #=> "This is line one\n"
  f.lineno   #=> 1
  f.gets     #=> "This is line two\n"
  f.lineno   #=> 2

答案 1 :(得分:0)

如果存在这样一行,您可以将以每个开头的第一个行号保留为谓词:

file= File.read("file_tobe_checked")
tabs = spaces = nil
line_no = 1
file.each do |line|
  tabs ||= line_no if line =~ /^\t/
  spaces ||= line_no if line =~ /^ /  
  line_no += 1

  if spaces && tabs
    STDERR <<  "The white spaces at the beginning of each line are not consistent.\n"
    STDERR << "Tab line: #{tabs}"
    STDERR << "Space line: #{spaces}"
  end
end