Check if directory is empty in Ruby

前端 未结 6 695
太阳男子
太阳男子 2020-12-14 15:57

How can I check to see if a directory is empty or not in Ruby? Is there something like:

Dir.exists?(\"directory\")

(I know that that functi

相关标签:
6条回答
  • 2020-12-14 16:01

    An empty directory should only have two links (. and ..). On OSX this works:

    File.stat('directory').nlink == 2
    

    ...but does not work on Linux or Cygwin. (Thanks @DamianNowak) Adapting Pan's answer:

    Dir.entries('directory').size == 2
    

    should work.

    0 讨论(0)
  • 2020-12-14 16:01

    Not straightforward but works perfect in *nix kind of systems.

    Dir.entries(directory_path) == ['.', '..']
    
    0 讨论(0)
  • 2020-12-14 16:04

    Here is my template for this one.FYI , i am looking for a certain match of files inside the source.

    mydir = "/home/to/mydir"
    
    Dir.chdir(mydir)
    
    if Dir.entries(mydir).select(|x| x != '.' && x != '..' && x =~ /\regex.txt\z/).size > 0
    
    
           do_something 
    
    elsif Dir.entries(mydir).select(|x| x != '.' && x != '..' && x =~ /\regex.txt\z/).size < 0
    
          do_something_else 
    
    else 
    
          puts "some warning message"
    end
    

    let me know if anything :)

    0 讨论(0)
  • 2020-12-14 16:14

    You can use entries to see all files and folders in a directory:

    Dir.entries('directory')
    => ['.', '..', 'file.rb', '.git']
    Dir.entries('directory').size <= 2 # Check if empty with no files or folders.
    

    You can also search for files only using glob:

    Dir.glob('directory/{*,.*}')
    => ['file.rb', '.git']
    Dir.glob('directory/{*,.*}').empty? # Check if empty with no files.
    
    0 讨论(0)
  • 2020-12-14 16:17

    As of Ruby 2.4.0, there is Dir.empty?

    Dir.empty?('/') # => false
    
    0 讨论(0)
  • 2020-12-14 16:22

    Ruby now has Dir.empty?, making this trivially easy:

    Dir.empty?('your_directory') # => (true|false)
    

    In Rubies prior to 2.4.0 you can just get a list of the entries and see for yourself whether or not it's empty (accounting for "." and ".."). See the docs.

    (Dir.entries('your_directory') - %w{ . .. }).empty?
    
    # or using glob, which doesn't match hidden files (like . and ..)
    Dir['your_directory/*'].empty?
    

    Update: the first method above used to use a regex; now it doesn't (obviously). Comments below mostly apply to the former (regex) version.

    0 讨论(0)
提交回复
热议问题