Check if directory is empty in Ruby

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)