Check if directory is empty in Ruby

前端 未结 6 698
太阳男子
太阳男子 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: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.
    

提交回复
热议问题