Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. File.exist? / directory? / basename / dirname / extname

File.exist? / directory? / basename / dirname / extname

Methods for checking file existence and decomposing file paths. Commonly used as preprocessing before file operations.

Syntax

# Check whether a file exists.
File.exist?("path")

# Check whether the path is a directory.
File.directory?("path")

# Check whether the path is a regular file.
File.file?("path")

# Get the filename from a path.
File.basename("path")
File.basename("path", "extension")  # Filename without the extension

# Get the directory part of a path.
File.dirname("path")

# Get the extension from a path.
File.extname("path")

Method List

MethodDescription
File.exist?Returns true if the file or directory exists.
File.file?Returns true if the path is a regular file.
File.directory?Returns true if the path is a directory.
File.basenameReturns the last component of the path (the filename).
File.dirnameReturns the directory portion of the path.
File.extnameReturns the file extension, including the dot.
File.joinJoins the arguments using the OS path separator.

Sample Code

path = "/home/user/documents/report.txt"

# Decompose the path.
puts File.basename(path)          # report.txt
puts File.basename(path, ".txt")  # report (without extension)
puts File.dirname(path)           # /home/user/documents
puts File.extname(path)           # .txt

# Check that the file exists before processing it.
filename = "sample.txt"
if File.exist?(filename)
  puts "The file exists."
  if File.file?(filename)
    puts "It is a regular file."
  end
else
  puts "The file does not exist."
end

# Use File.join to safely build a path.
directory = "/home/user"
file = "data.csv"
full_path = File.join(directory, "documents", file)
puts full_path  # /home/user/documents/data.csv

# Branch logic based on the file extension.
file_list = ["image.png", "doc.txt", "script.rb", "data.csv"]
file_list.each do |f|
  puts "#{f}: #{File.extname(f)}"
end

Overview

The class methods of the File class are specialized for working with file paths. Because they let you retrieve path information without actually opening a file, they are convenient for pre-processing checks.

Use File.join rather than string concatenation to build paths. Windows and Unix-like systems use different path separators, but File.join generates the correct path regardless of the environment. Use File.exist? instead of the older File.exists?, which was removed in Ruby 3.2.

If you find any errors or copyright issues, please .