leemour
leemour

Reputation: 12013

How to check that a Ruby file is empty?

I have a text file for example. What is the best way to check in Ruby that a file is empty? File.size('test.rb') == 0 looks ugly.

Upvotes: 42

Views: 23133

Answers (5)

Michael Durrant
Michael Durrant

Reputation: 96504

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

Upvotes: 2

Thorin
Thorin

Reputation: 2034

I think should check like this:

def file_empty?(file_path) 
  !(File.file?(file_path) && !File.zero?(file_path))
end

so we do not need to worry about file exist or not.

File.zero?('test.rb') return false if file not exist

Upvotes: 1

bigtunacan
bigtunacan

Reputation: 4986

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.

Upvotes: 6

jaynetics
jaynetics

Reputation: 1313

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

Upvotes: 5

Matt
Matt

Reputation: 1198

You could use the zero? method:

File.zero?("test.rb")

Upvotes: 65

Related Questions