---
title: "Ruby 2.4 now has Dir.empty? and File.empty? methods"
description: "No more platform specific code to check empty directories"
canonical_url: "https://www.bigbinary.com/blog/dir-emtpy-included-in-ruby-2-4"
markdown_url: "https://www.bigbinary.com/blog/dir-emtpy-included-in-ruby-2-4.md"
---

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

No more platform specific code to check empty directories

- Author: Ratnadeep Deshmane
- Published: February 28, 2017
- Categories: Ruby 2.4, Ruby

In Ruby, to check if a given directory is empty or not, we check it as

```ruby

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 `..`.

## Dir.empty?

Considering all this, Ruby has finally
[included](https://bugs.ruby-lang.org/issues/10121) a new method `Dir.empty?`
that takes directory path as argument and returns boolean as an answer.

Here is an example.

```ruby

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

```

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.

```ruby

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

```

After introducing `Dir.empty?` it makes sense to
[add](https://bugs.ruby-lang.org/issues/9969) `File.empty?` as an alias to
`File.zero?`

```ruby

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

```

## Links

- [Human page](https://www.bigbinary.com/blog/dir-emtpy-included-in-ruby-2-4)
