开发者

Strange behaviour with directories and FileTest.directory

开发者 https://www.devze.com 2023-04-08 19:06 出处:网络
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 di

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)
  d开发者_运维知识库ir = 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?


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:

FileTest.directory?('dira/dirb')

and not just

FileTest.directory?('dirb')

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号