Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that a Ruby file is empty?

Tags:

ruby

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.

like image 289
leemour Avatar asked Apr 12 '13 23:04

leemour


People also ask

How to check a file is empty in Ruby?

File. zero?('test. rb') will return true is the file is empty, but it will return false if the file is not found.

How can I check if a file is empty?

The easiest way to check is to stream the data within the file and check its length. If there are 0 bytes in the file, or rather, if the length of the data is equal to 0 , the file is empty: router.

How do I check a file in Ruby?

We can check if a file exists in Ruby by using the exists?() method of the File class. This method returns a Boolean value signifying if the file exists or not.

How check if file is empty C#?

Now FileInfo. Length will show a size that is not zero. A solution for this is to check for Length < 6, based on the max size possible for byte order mark. If your file can contain single byte or a few bytes, then do the read on the file if Length < 6 and check for read size == 0.


2 Answers

You could use the zero? method:

File.zero?("test.rb") 
like image 148
Matt Avatar answered Sep 23 '22 23:09

Matt


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.

like image 39
bigtunacan Avatar answered Sep 22 '22 23:09

bigtunacan