We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
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.
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
Considering all this,
Ruby has finally
a new method
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.
To check if a file is empty,
This checks if the file exists and has zero size.
1 2File.zero?('/Users/rtdp/Documents/todo.txt') #=> true 3
it makes sense to
File.empty? as an alias to
1 2File.empty?('/Users/rtdp/Documents/todo.txt') #=> true 3