Ruby类正在输出文件和目录
为什么在“print”\n“+f”行下面的类会输出目录和文件名? 我只想输出文件,但目录也被输出Ruby类正在输出文件和目录,ruby,Ruby,为什么在“print”\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] == ?.
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
考虑改用Ruby标准方法。考虑改用Ruby标准方法。它在评论中说:
# do whatever you want with f, which is a filename within the
# given directory (not fully-qualified)
钥匙为“不完全合格”零件。您需要执行以下操作:
if !FileTest.directory? (path + File::SEPARATOR + f)
它在评论中写道:
# do whatever you want with f, which is a filename within the
# given directory (not fully-qualified)
钥匙为“不完全合格”零件。您需要执行以下操作:
if !FileTest.directory? (path + File::SEPARATOR + f)
您需要
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
您需要
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