This blog is part of our Ruby 2.4 series.
In Ruby, to check if a given directory is empty or not, we check it as
1 2Dir.entries("/usr/lib").size == 2 #=> false 3Dir.entries("/home").size == 2 #=> true 4
Every directory in Unix filesystem contains at least two entries. These are .(current directory) and ..(parent directory).
Hence, the code above checks if there are only two entries and if so, consider a directory empty.
Again, this code only works for UNIX filesystems and fails on Windows machines, as Windows directories don't have . or ...
Dir.empty?
Considering all this, Ruby has finally included a new method Dir.empty? that takes directory path as argument and returns boolean as an answer.
Here is an example.
1 2Dir.empty?('/Users/rtdp/Documents/posts') #=> true 3
Most importantly this method works correctly in all platforms.
File.empty?
To check if a file is empty, Ruby has File.zero? method. This checks if the file exists and has zero size.
1 2File.zero?('/Users/rtdp/Documents/todo.txt') #=> true 3
After introducing Dir.empty? it makes sense to add File.empty? as an alias to File.zero?
1 2File.empty?('/Users/rtdp/Documents/todo.txt') #=> true 3