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.)
To check if a file is empty, Ruby has File. zero? method. This checks if the file exists and has zero size.
File. zero?('test. rb') will return true is the file is empty, but it will return false if the file is not found.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With