2011-04-26 112 views
2

進出口使用搜索在當前目錄下只有

Find.find("c:\\test") 

搜索的目錄文件。我只想在這個級別搜索dir,因此c:\ test中的任何目錄都不會被搜索到。

是否有另一種方法可以使用?

感謝

回答

4
# Temporarily make c:\test your current directory 
Dir.chdir('c:/test') do 
    # Get a list of file names just in this directory as an array of strings 
    Dir['*'].each do |filename| 
    # ... 
    end 
end 

或者:

# Get a list of paths like "c:/test/foo.txt" 
Dir['c:/test/*'] do |absolute| 
    # Get just the filename, e.g. "foo.txt" 
    filename = File.basename(absolute) 
    # ... 
end 

有了這兩個,你可以如果你喜歡,只需將文件名寫入數組中:

files = Dir.chdir('c:/text'){ Dir['*'] } 
files = Dir['c:/text/*'].map{ |f| File.basename(f) } 
3

Findprune方法,可以跳過當前的文件或目錄:

跳過當前文件或目錄, 重新啓動下一個 進入循環。如果當前文件是 目錄,則該目錄將不會被遞歸地輸入 。僅在 與 Find :: find關聯的塊內有意義。

Find.find("c:\\test") do |path| 
    if FileTest.directory?(path) 
    Find.prune # Don't look any further into this directory. 
    else 
    # path is not a directory, so must be file under c:\\test 
    # do something with file 
    end 
end 
0

您可以使用Dir.foreach(),例如,列出在c的所有文件:\測試

Dir.foreach("c:\\test") {|x| puts "#{x}" }