2011-10-25 8 views
1

なぜ、下のクラスはディレクトリ "print" \ n "+ f"のディレクトリ名とファイル名を出力しますか? ファイルを出力したいだけですが、ディレクトリも出力されています。Rubyクラスがファイルとディレクトリを出力しています

class Sort 



    require 'find' 

    directoryToSort = "c:\\test" 

    total_size = 0 

    Find.find(directoryToSort) do |path| 
    if FileTest.directory?(path) 
     if File.basename(path)[0] == ?. 
     Find.prune  # Don't look any further into this directory. 
     else 
     Dir.foreach(path) do 
     |f| 
     # do whatever you want with f, which is a filename within the 
     # given directory (not fully-qualified) 
     if !FileTest.directory? f 
     print "\n"+f 
     end 
     end 
     next 
     end 
    else 
    end 
    end 

end 

答えて

4

それはすぐそこのコメントで述べている:「完全修飾ではない」部分である

# do whatever you want with f, which is a filename within the 
# given directory (not fully-qualified) 

キー。あなたはそれがあなたはおそらく、これらの線に沿って何かをしたいファイル名

だかどうかを確認するFile.directory?(filename)が必要

if !FileTest.directory? (path + File::SEPARATOR + f) 
+1

+1 Slartibartfast!その素晴らしいフィヨルドに感謝します! – Tilo

1

代わりにRuby標準File.directory?メソッドを使用することを検討してください。

+0

これと同じ結果が試されました。 –

1

....

これがためのヘルパーメソッドです:ようにあなたが何かをする必要があり再帰的なディレクトリの下降を行い、ファイル名が特定の正規表現と一致する場合は に応じてブロックを実行します。あなたには少し残念ですが、おそらくこれが役に立ちます。

# recursiveDirectoryDescend                                                              
#  do action for files matching regexp 
# 
# (not very elegant solution, but just for illustration purposes. Pulled from some very old code.) 


def recursive_dir_descend(dir,regexp,action) 
    olddir = Dir.pwd 
    dirp = Dir.open(dir) 
    Dir.chdir(dir) 
    pwd = Dir.pwd 

    for file in dirp 
    file.chomp 
    next if file =~ /^\.\.?$/ # ON UNIX, ignore '.' and '..' directories 

    filename = "#{pwd}/#{file}" 
    if File.directory?(filename)     # CHECK IF DIRECTORY 
     recursive_dir_descend(filename,regexp,action) 
    else 
     if file =~ regexp 
     eval action # execute action on filename                                                        
     end 
    end 
    end 
    Dir.chdir(olddir) 
end 
関連する問題