Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if directory is empty in Ruby

Tags:

directory

ruby

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

like image 533
Mark Szymanski Avatar asked Feb 20 '11 18:02

Mark Szymanski


People also ask

How can I tell if a Ruby file is empty?

To check if a file is empty, Ruby has File. zero? method. This checks if the file exists and has zero size.

How do I check if a csv file is empty in Ruby?

File. zero?('test. rb') will return true is the file is empty, but it will return false if the file is not found.

How do you delete a directory in ruby?

Ruby provides several methods for removing directories, but you really only need remove_dir. Dir. delete and FileUtils. rmdir will only work if the directory is already empty.


1 Answers

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.

like image 185
coreyward Avatar answered Sep 23 '22 04:09

coreyward