February 28, 2017
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
Dir.entries("/usr/lib").size == 2 #=> false
Dir.entries("/home").size == 2 #=> true
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 ...
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.
Dir.empty?('/Users/rtdp/Documents/posts') #=> true
Most importantly this method works correctly in all platforms.
To check if a file is empty, Ruby has File.zero? method. This checks if the
file exists and has zero size.
File.zero?('/Users/rtdp/Documents/todo.txt') #=> true
After introducing Dir.empty? it makes sense to
add File.empty? as an alias to
File.zero?
File.empty?('/Users/rtdp/Documents/todo.txt') #=> true
If this blog was helpful, check out our full blog archive.