Ruby - Check if a Path is a File or a Directory

1. Introduction

In file system operations, often there's a need to determine whether a given path points to a regular file or a directory. Knowing this is essential in many contexts, such as when writing file system utilities or processing a list of paths. Ruby provides straightforward methods via the File and Dir classes to help determine the type of a given path. This article will walk through a simple Ruby program to check if a path is a file or a directory.

2. Program Steps

1. Define the path that you want to inspect.

2. Use the File.file? method to check if the path is a file.

3. Use the File.directory? method to check if the path is a directory.

4. Print the result based on the checks from steps 2 and 3.

3. Code Program

# Specify the path you want to inspect
path = "sample_path"
# Check if the path is a file or a directory
if File.file?(path)
  puts "#{path} is a file."
elsif File.directory?(path)
  puts "#{path} is a directory."
else
  puts "#{path} does not exist or is of an unknown type."
end

Output:

sample_path is a file.
Or
sample_path is a directory.
Or
sample_path does not exist or is of an unknown type.

Explanation:

1. path = "sample_path": Here, we specify the name or path we want to check.

2. File.file?(path): The file? method from the File class returns true if the given path points to a regular file.

3. File.directory?(path): The directory? method from the File class returns true if the given path points to a directory.

4. Based on the checks, we print out whether the path points to a file, a directory, or doesn't exist/unknown type.


Comments