为什么下面的类输出目录和文件名在线“打印”\ n“+ f”? 我只想输出文件,但目录也在输出。
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
答案 0 :(得分:4)
它在评论中说:
# do whatever you want with f, which is a filename within the
# given directory (not fully-qualified)
关键是“不完全合格”的部分。你需要做类似的事情:
if !FileTest.directory? (path + File::SEPARATOR + f)
答案 1 :(得分:1)
请考虑使用Ruby标准File.directory?方法。
答案 2 :(得分:1)
您需要File.directory?( filename )
来检查它是否是文件名
你可能想要沿着这些方向做点什么......
这是一个辅助方法,用于执行递归目录下降和执行块依赖 如果文件名与某些正则表达式匹配..对你来说有点矫枉过正,但也许这会有所帮助。
# 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