Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
FileTest#size?
(::path | ::io file_name) -> ::Integer?
File.size?(object) → integer or nil
file.c
View on GitHub ↗
static VALUE
rb_file_size_p(VALUE obj, VALUE fname)
{
struct stat st;
if (rb_stat(fname, &st) < 0) return Qnil;
if (st.st_size == 0) return Qnil;
return OFFT2NUM(st.st_size);
}
Returns the size in bytes of the given object if the entry exists and has non-zero size, nil otherwise; the object may be a path or an IO object:
Example
# Regular file. path = '/tmp/t.tmp' File.write(path, 'foo') File.size?(path) # => 3 # Non-zero size. File.write(path, '') File.size?(path) # => nil # Zero size. File.delete(path) # Clean up. File.size?(path) # => nil # Non-existent. # Directory. path = '/tmp/foo/' Dir.mkdir(path) File.size?(path) # => 4096 # Non-zero size. Dir.rmdir(path) # Clean up. File.size?(path) # => nil # Non-existent.