/ / Čísla Ruby print line [duplicate] - rubín, riadok, medzery

Ruby print line lines [duplicate] - rubín, riadok, medzery

Snažím sa skontrolovať riadok súboru podľa riadku prezačiatočný biely priestor. Chcem, aby všetky riadky začali s priestorom alebo záložkou nie oboma. Ak existuje riadok začínajúci medzerou a prašníkom, ktorý začína na karte v súbore, kód uvedený nižšie bude tlačiť upozornenie, ale navyše chcem vytlačiť 2 riadky, ktoré začínajú medzerou a začína s tab len na zobrazenie užívateľa, a Im prilepený na to, ako získať čísla liniek a veci. Pomoc!! Môj kód vyzerá takto.

    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

odpovede:

0 pre odpoveď č. 1

Ruby má niekoľko špeciálnych premenných, z ktorých jedna je $. čo je číslo aktuálne čítaného riadku.

Môžete tiež použiť IO lineno metóda.

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 onen"
f.lineno   #=> 1
f.gets     #=> "This is line twon"
f.lineno   #=> 2

0 pre odpoveď č. 2

Môžete si ponechať číslo prvého riadku, ktoré začína s každým ako predikát, ak existuje takýto riadok:

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