Skip to content

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

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.
See also #size #socket? #setuid? #sticky? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0