Check if directory is empty in Ruby

杀马特。学长 韩版系。学妹 提交于 2019-12-17 22:57:37

问题


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 function doesn't exist.)


回答1:


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.




回答2:


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.



回答3:


As of Ruby 2.4.0, there is Dir.empty?

Dir.empty?('/') # => false



回答4:


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.




回答5:


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

Dir.entries(directory_path) == ['.', '..']



回答6:


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 :)



来源:https://stackoverflow.com/questions/5059156/check-if-directory-is-empty-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!