2011-08-24 58 views
0

我想編寫一個程序,從用戶獲得一個路徑,然後轉到該目錄和所有的子目錄,並收集所有的txt文件。但是「。」和「..」打擾我,當我迭代迭代目錄。請幫我解決這個問題。 這是我的代碼:刪除「。」和「..」在與目錄工作

def detect_files(path) 
      Dir.foreach(path) do |i| 
     if (i != "." or i !="..") 
      if (File.directory?(i)) 
       detect_files(i) 
      end 
      if (i.reverse.start_with?("txt.")) 
       @files[i]=[] 
      end 
     end 
    end 

end 
+2

而不是包裝完整的塊成如 - 聲明,你應該考慮使用'next if '。這爲您節省了一級縮進,並使您的代碼更具可讀性。 –

回答

4

的條件應該是:

if (i != "." and i != "..") 
  • 如果i="."然後i != "."將是錯誤的製作條件的錯誤,並"."不會被處理
  • 如果i=".."那麼i != "."將爲true,但i != ".."將爲false,使條件爲false,並且".."將不被處理。
  • 如果i有任何其他值,那麼and的兩側將爲真,if的主體將被執行。
1
Dir.foreach(path) do |i| 
    next if %w(. ..).include?(i) 
    # rest of your code 
end 

您的當前版本的if一個錯誤的條件:你要(i != '.' AND i != '..')

1
all_txt_files = Dir['**/*.txt'] 
0

你可以嘗試只是在做這樣的事情

def detect_files(path) 
    p1 = File.join(path, '**', '*.txt') 
    @files = Dir[p1] 
end 
0

嘗試這樣的:

Dir.foreach('/path/to/dir') do |item| 
    next if item == '.' or item == '..' 
    # do work on real items 
end 

OR

Dir.glob('/path/to/dir/*.rb') do |rb_file| 
    # do work on files ending in .rb in the desired directory 
end