2017-05-14 65 views
0

我正在從文件say-list.txt中讀取數據,並檢查list.txt中的字符串是否存在於目錄中的多個文件中。 (E:\ work ...)。以下是我的代碼,其按預期工作。Ruby訪問數組值

pool = '' 
rows = Array[] 
id_files = Dir.glob("E:\work'*-access.txt") 

value=File.open('E:\nando\list.txt').read 
value.each_line do |line| 
    line.chomp! 
    id_files.each do |file_name| 
     text = File.read(file_name) 
     new_content = text.gsub(/#{Regexp.escape(line)}\,\s/, '').gsub(/#{Regexp.escape(line)}/, '') 

     unless text == new_content 

     text.each_line do |li| 
      if li.match(/#{Regexp.escape(line)}/) then 
      rows << li # I didn't complete the array part 
      puts rows[0] 
      puts rows[1] 
      pool = li.split(" ")[0] 
      end 
     end 
     File.open('E:\Removed_users.txt', 'a') { |log| 
     log.puts "Removed from: #{file_name}" 
     log.puts "Removed id : #{line}" 
     log.puts "Removed from row :#{pool}" 
     log.puts "*" * 50 
     } 
     File.open(file_name, "w") { |file| file.puts new_content } 
     end 
    end 
end 

我試圖提高代碼在下面的格式打印到日誌file.Eg字符串 - 從目錄中的文件的一類\234公頃和蓋\ 7y6t5。

Removed class\234ha from row = id and dept 
Removed cap\7y6t5 from row = id 

E:\工作\樣本access.txt

CDA created on September 20th 1999 
Owner: Edward Jenner 
Access IDs, 
id = class\234ha, class\poi23, class\opiuj, cap\7y6t5 
dept = sub\6985de, ret\oiu87, class\234ha 
rec = ret\oiu87 

我能夠使它只打印單個time.i.e.類\234公頃我得到輸出

Removed from: E:\work\sample-access.txt 
Removed user : class\234ha 
Removed from row = id 

理想應該是

Removed from: E:\work\sample-access.txt 
Removed user : class\234ha 
Removed from row = id and dept 

我嘗試使用陣列的選擇,但我沒有得到的結果如預期,我不希望完全重寫代碼或邏輯。 Ruby專家,任何建議都會非常有幫助。謝謝。

回答

0

可能是最簡單的解決方案(以最小的變化),你的問題是

# ... your code 
pool = [] # define array for current match 
text.each_line do |li| 
    # ... your code 
    pool << li.split(" ")[0] # add to array 
# ... your code 
log.puts "Removed from row :#{pool.join(' and ')}" # list all the ids joined by and 
# ... your code 

我希望我沒有忽視一些

+0

感謝您的建議,但它的附加價值像下面,而不是打印每單價值從行移除採樣access.txt :行 '從刪除從刪除行採樣access.txt :ID 從移除R:ID和DEP從刪除 ate-access.txt 從行中刪除:dep和automation' – dev

+0

對不起,我不理解評論(可能是因爲在評論中格式化)。對於每一行(= id),它將所有從當前文件中刪除的段保存在循環中 - 「pool」包含每個文件的段(=行)。我根據你的問題回答了這個問題。 – insider

+0

感謝您的時間。我以不同的方式工作。 – dev