2012-12-30 62 views
1

我想寫一些代碼做以下的事情:匹配信息

  • 如果輸入的文件(如:"file.out")包含像"n failures, n errors""n failures, 0 errors",或"0 failures, n errors"(其中n >= 1)的信息,然後puts "script failed"(因爲顯示失敗或錯誤)。

  • 如果輸入文件包含信息:"0 failures, 0 errors",然後puts "script passed"(因爲沒有故障和錯誤顯示)。

我想我需要寫類似下面的東西(但並不如我所料的情況下正常工作):

if open("#{file}.out").grep(/[1-9][0-9]* failures|[1-9][0-9]* errors/).length > 0 
    puts "script passed" 
else 
    puts "script failed" 
end 

我怎樣才能做到這一點?

回答

4
def check_script file 
    open(file) do |io| 
    io.read =~ /(\d+)\s+failures,\s+(\d+)\s+errors/ 
    puts "script #{$1 == "0" && $2 == "0" ? "passed" : "failed"}" 
    end 
end 

用法:

check_script("file.out") 
+0

這個解決方案工作得很好,當我的文件,包括像信息:0失敗, ** 1 **錯誤(在這種情況下,系統返回「腳本失敗「如預期)。然而,當我的文件包含信息:0失敗,** 2 **錯誤,系統返回「腳本通過,但我期望腳本將返回」腳本失敗「 – battleship

+0

此外,當我的腳本有信息:」0失敗,0錯誤「,系統返回」腳本失敗「,但我期望返回的信息是」腳本通過「 – battleship

+0

@battleship你確定該文件不包括'0失敗,0錯誤'的地方除了0失敗,2錯誤'?我懷疑你有什麼你說的你有 – sawa

2

假設文件包含

info: 0 failures, 0 errors 

代碼將

(File.open("#{file}.out").read).scan(/info: ([0-9]+) failures, ([0-9]+) errors/) do |failures, errors| 
    puts (failures.to_i > 0 || errors.to_i > 0) ? "script failed" : "script passed" 
end 
+0

這個解決方案對我的場景也很好。非常感謝你的出色答案。 – battleship

+0

我很高興我的幫助:) –

相關問題