Ruby 2.4 now has Dir.empty? and File.empty? methods

Ratnadeep Deshmane

By Ratnadeep Deshmane

on 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

2Dir.entries("/usr/lib").size == 2       #=> false
3Dir.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.

2Dir.empty?('/Users/rtdp/Documents/posts')   #=> true

Most importantly this method works correctly in all platforms.


To check if a file is empty, Ruby has method. This checks if the file exists and has zero size.

1'/Users/rtdp/Documents/todo.txt')    #=> true

After introducing Dir.empty? it makes sense to add File.empty? as an alias to

2File.empty?('/Users/rtdp/Documents/todo.txt')    #=> true

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.