How to check that a Ruby file is empty?

As of Ruby 2.4.0, there is File.empty?.

(Note that it always returns false if you pass it a directory, whether that directory is empty or not: File.empty?('/') # => false. So use Dir.empty? for that instead, or Pathname#empty? which works for both files and directories.)


You could use the zero? method:

File.zero?("test.rb")

One different approach is to iterate over each line and do stuff for each iteration. 0 lines = 0 iterations = no extra code needed.


File.size?('test.rb') evaluates to nil if the file is empty or it does not exist. File.zero?('test.rb') will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method.

As an example in the topic creator's question they specifically asked, "What is the best way to check in Ruby that a file is empty?" The accepted answer does this correctly and will raise a No such file or directory error message if the file does not exist.

In some situations we may consider the lack of a file to be "equivalent" to an empty file.

Tags:

Ruby