與Ruby/Rails working with gsub and arrays類似。用紅寶石中的字符串替換另一個字符串中的字符串
我有兩個數組,「errors」和「human_readable」。
我想通過一個指定的文件讀取「logins.log」取代 錯誤[X]與human_readable [X]
我不在乎輸出變,標準輸出是罰款。
errors = ["0xC0000064", "0xC000006A", "0xC0000071", "0xC0000072", "0xC0000234"] human_readable = ["Unknown User", "Bad Password", "Expired Password", "Account Disabled", "Account Locked"] file = ["logins.log"] file= File.read() errors.each
輸了...
我很抱歉,我知道這是一個愚蠢的問題,我想,但迭代我收到糾結了。
什麼工作對我來說(我相信其他的答案是有效的,但是這是我更容易理解)
#Create the arrays errors = ["0xC0000064", "0xC000006A", "0xC0000071", "0xC0000072", "0xC0000234"] human_readable = ["Unknown User", "Bad Password", "Expired Password", "Account Disabled", "Account Locked"]
#Create hash from arrays zipped_hash = Hash[errors.zip(human_readable)]
#Open file and relace the errors with their counterparts new_file_content = File.read("login.log").gsub(Regexp.new(errors.join("|")), zipped_hash)
#Dump output to stdout puts new_file_content
這是真棒,併成爲了很多東西的模板,謝謝一百萬。
+1對於第二種解決方案,整潔的 – Nimir
第二種解決方案很聰明,很好猜! – MrYoshiji
謝謝。把解決方案放在後面(假設我沒有錯過任何東西)。 – TheFiddlerWins