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#exist?

(::path | ::io file_name) -> bool
File.exist?(object) → true or false

Return whether the specified object, a string path or IO object, exists:

Example
# String paths.
File.exist?('README.md') # => true
File.exist?('.')         # => true
filepath = 't.tmp'
File.exist?(filepath)    # => false
File.write(filepath, 'foo')
File.exist?(filepath)    # => true
# File (IO object).
file = File.new(filepath)
File.exist?(file)        # => true
file.close               # Clean up.
File.unlink(filepath)    # Clean up.

Follows symbolic links:

Example
# Symbolic links.
File.symlink('README.md', 'README.link')
File.symlink('nosuch', 'BROKEN.link')
File.exist?('README.link')  # => true
File.exist?('BROKEN.link')  # => false
File.unlink('README.link')  # Clean up.
File.unlink('BROKEN.link')  # Clean up.
See also #executable_real? #file? #executable? #grpowned? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0