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.
File. zero?('test. rb') will return true is the file is empty, but it will return false if the file is not found.
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.
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.
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.
You could use the zero?
method:
File.zero?("test.rb")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With