开发者

Check if directory is empty in Ruby

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

Dir.exists?("directory")

(开发者_如何学CI know that that function doesn't exist.)


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.


As of Ruby 2.4.0, there is Dir.empty?

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


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.


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.


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

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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜