目录和 FileTest.directory 的奇怪行为
我正在研究这个 ruby 脚本,我必须递归地查看从特定目录开始的所有子目录。但由于某种原因 FileTest.directory?似乎只能识别与脚本位于同一文件夹中的目录
def files(start)
dir = Dir.open (start)
dir.each do |x|
p "#{x}: #{FileTest.directory?(x)}"
if FileTest.directory?(x) && x != '.' && x != '..'
start = x
files (start)
end
end
end
files '.'
假设我的目录结构如下:在当前目录中,我有一个文件 a.txt 和两个名为“b”和 drct2 的目录。 “b”包含另一个目录“c”,“drct”包含另一个目录“dir3”。当从当前目录运行时,上面的代码可以识别“b”和“b”。 'drct2' 作为目录,但不作为其子目录。谁能想到 FileTest.directory 的原因吗?是这样的吗?
I am working on this ruby script where I have to recursively look inside all the subdirectories starting at a particular directory. But for some reason FileTest.directory? only seems to recognise a directory if it is located in the same folder as the script
def files(start)
dir = Dir.open (start)
dir.each do |x|
p "#{x}: #{FileTest.directory?(x)}"
if FileTest.directory?(x) && x != '.' && x != '..'
start = x
files (start)
end
end
end
files '.'
Supposed my directory structure is as follows: In the current dir I have a file a.txt and two directories called 'b' and drct2. 'b' contains another directory 'c' and 'drct' contains another directory 'dir3'. The code above when run from the current directory recognizes 'b' & 'drct2' as directories but not their sub directories. Can anyone think of a reason why FileTest.directory? is behaving this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要提供 FileTest 的完整路径,因为它相对于您当前的目录工作,
所以如果您有 dira ->迪尔布-> filec 你需要运行:
而不仅仅是
顺便说一句,我建议你研究 Dir.glob('**/*') 方法 - 它很有可能做你需要做的开箱即用的事情。
You need to give a full path to the FileTest as it works relative to your current dir
So if you have dira -> dirb -> filec you need to run:
and not just
BTW I suggest you look into Dir.glob('**/*') method - there is a good chance it does what you need to do out-of-the-box.