Search code examples
rubydirectorytraversaldirsubdirectory

`File.directory?` method always returns `false` when passed an element of Dir.entries


I am pretty new to ruby. I'm trying to print directory structure in ruby. Following is the code that I'm using :

Repo_dir = 'path_to_the_dir'

dir = Dir.entries(Repo_dir)
dir.each do |folder|
    if folder == '.' or folder == '..'
        print ""
    else    
        print "#{folder}\n"
        if File.directory?(folder) 
            print "we are here !"
            sub_dir = Dir.entries("#{Repo_dir}#{File::SEPARATOR}#{folder}")
                sub_dir.each do |subdir|
                    print "#{subdir}\n"
                end
        end

    end

end

This code just prints the structure of the parent directory(dir array). It does not print the files/folders inside the entries of my 'dir' object, that is, it never prints the subdirectories, nor "we are here !". File.directory? method always returns false.

Ruby version : 1.9.3


Solution

  • You need to add the parent as Dir.entries doesn't include the target when enumerating its contents.

    File.directory?(File.join(Repo_dir, folder))
    

    File.join is a platform independent way of adding separators between directories and files. Think of it like

    Repo_dir + '/' + folder
    

    Or

    Repo_dir + '\' + folder
    

    Try this one as well:

    #!/usr/bin/env ruby
    
    def show_tree_of_dirs(dir)
      if not dir =~ /\/\.\.?$/ and File.directory?(dir)
        puts dir
    
        Dir.entries(dir).each do |e|
          show_tree_of_dirs(File.join(dir, e))
        end
      end
    end
    
    (dir = ARGV.shift) and show_tree_of_dirs(dir)
    

    Or

    #!/usr/bin/env ruby
    
    def show_tree_of_dirs(dir)
      if File.directory?(dir)
        puts dir
    
        Dir.glob(File.join(dir, '*')).each do |e|
          show_tree_of_dirs(e)
        end
      end
    end
    
    (dir = ARGV.shift) and not dir =~ /\/\.\.?$/ and show_tree_of_dirs(dir)